2024-04-18 17:13:08 发布
网友
我有一个浮点数,比如135.12345678910。我想将该值连接到字符串,但只需要135.123456789。使用print,我可以很容易地做到这一点,比如:
135.12345678910
135.123456789
print "%.9f" % numvar
我的原始号码是numvar。有什么简单的方法可以做到这一点吗?
numvar
使用round:
round
>>> numvar = 135.12345678910 >>> str(round(numvar, 9)) '135.123456789'
使用Python<;3(例如2.6[见注释]或2.7),有两种方法可以做到这一点。
# Option one older_method_string = "%.9f" % numvar # Option two newer_method_string = "{:.9f}".format(numvar)
但是请注意,对于高于3的Python版本(例如3.2或3.3),选项2是preferred。
关于选项2的更多信息,我建议this link on string formatting from the Python documentation。
关于选项一的更多信息,this link will suffice and has info on the various flags。
Python 3.6(于2016年12月正式发布)添加了f字符串文本see more information here,它扩展了str.format方法(使用大括号使f"{numvar:.9f}"解决了原始问题),也就是说
f
str.format
f"{numvar:.9f}"
# Option 3 (versions 3.6 and higher) newest_method_string = f"{numvar:.9f}"
解决问题。查看@或Duan的答案以获取更多信息,但此方法是快速。
为了清楚起见,可以使用f-string格式。这与format方法的语法几乎相同,但使其更好一些。
format
示例:
print(f'{numvar:.9f}')
有关新f字符串的更多信息:
使用
round
:使用Python<;3(例如2.6[见注释]或2.7),有两种方法可以做到这一点。
但是请注意,对于高于3的Python版本(例如3.2或3.3),选项2是preferred。
关于选项2的更多信息,我建议this link on string formatting from the Python documentation。
关于选项一的更多信息,this link will suffice and has info on the various flags。
Python 3.6(于2016年12月正式发布)添加了
f
字符串文本see more information here,它扩展了str.format
方法(使用大括号使f"{numvar:.9f}"
解决了原始问题),也就是说解决问题。查看@或Duan的答案以获取更多信息,但此方法是快速。
Python3.6 | 2017
为了清楚起见,可以使用f-string格式。这与
format
方法的语法几乎相同,但使其更好一些。示例:
有关新f字符串的更多信息:
相关问题 更多 >
编程相关推荐