2

Python keeps using fixed format for large floats:

>>> 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++:

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

str(x)

when x is a float?

1
  • "%.2e" % 1e-10 Commented Feb 22, 2020 at 13:55

1 Answer 1

3

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

"{:.2e}".format(1.0e-7)
Sign up to request clarification or add additional context in comments.

3 Comments

I don't want to always use scientific notation: it will print '1.000000e+02' instead of 100. Float comes in a variable and it may be 100.0 or 1e+10. How do I make it behave like C++ example?
I think the C++ std::to_string function isn't specified so exactly; just choose a bound (say, 1e9) and write something like ('{:e}' if abs(x) >= 1e9 else '{}').format(number).
@user2052436 See my other example in my post where you can set the precision of the representation. But if you want to have a custom precision for when to use scientific notation you could just use if conditions for when to format with scientific notation or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.