将浮点数转换为一定精度,然后复制为字符串

2022-10-19Python开发问题
2

本文介绍了将浮点数转换为一定精度,然后复制为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个浮点数,比如 135.12345678910.我想将该值连接到一个字符串,但只需要 135.123456789.使用打印,我可以通过执行以下操作轻松做到这一点:

I have a floating point number, say 135.12345678910. I want to concatenate that value to a string, but only want 135.123456789. With print, I can easily do this by doing something like:

print "%.9f" % numvar

numvar 是我的原始号码.有没有简单的方法可以做到这一点?

with numvar being my original number. Is there an easy way to do this?

推荐答案

使用 Python <3(例如 2.6 [见评论] 或 2.7),有两种方法.

With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.

# Option one
older_method_string = "%.9f" % numvar

# Option two
newer_method_string = "{:.9f}".format(numvar)

但请注意,对于高于 3 的 Python 版本(例如 3.2 或 3.3),选项二是 首选.

But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.

有关选项二的更多信息,我建议 this link on string formatting from thePython 文档.

For more information on option two, I suggest this link on string formatting from the Python documentation.

关于选项一的更多信息,这个链接就足够了,并且有各种标志的信息.

And for more information on option one, this link will suffice and has info on the various flags.

Python 3.6(2016 年 12 月正式发布),添加了 f 字符串字面量,在此处查看更多信息,它扩展了 str.format 方法(使用大括号,例如 f"{numvar:.9f}" 解决了原来的问题),也就是

Python 3.6 (officially released in December of 2016), added the f string literal, see more information here, which extends the str.format method (use of curly braces such that f"{numvar:.9f}" solves the original problem), that is,

# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"

解决问题.查看@Or-Duan 的答案以获取更多信息,但此方法快速.

solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.

这篇关于将浮点数转换为一定精度,然后复制为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11