简体   繁体   English

浮动到字符串通用格式

[英]Float to string general format

Python keeps using fixed format for large floats: Python 一直对大浮点数使用固定格式:

>>> str(1.0e-2)
'0.01'
>>> str(1.0e+2)
'100.0'
>>> str(1.0e-10)
'1e-10'
>>> str(1.0e+10)
'10000000000.0'

How can I make it print 1e+10 in the last case, similar to c++:在最后一种情况下,如何使它打印1e+10 ,类似于 C++:

std::cout << 1.0e-2 << '\n'
          << 1.0e+2 << '\n'
          << 1.0e-10 << '\n'
          << 1.0e+10 << '\n';

0.01
100
1e-10
1e+10

I don't want to always use scientific notation.我不想总是使用科学记数法。

How do I make Python conversion behave similar to C++ general format for我如何使 Python 转换的行为类似于 C++ 的通用格式

str(x)

when x is a float?x是浮点数时?

You can do this with scientific notation你可以用科学记数法做到这一点

"{:e}".format(1.0e-7)

Or you can choose how many digits to show after the decimal by adding .n before the e或者您可以通过在e前添加.n来选择小数点后显示的位数

"{:.2e}".format(1.0e-7)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM