Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert floating point number to a certain precision, and then copy to string

People also ask

Can you convert a float to a string?

We can convert float to String in java using String. valueOf() and Float. toString() methods.

Which function converts float data to string?

toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.

What function can be used to change a floating-point value to a string value in Python?

Python Convert float to String We can convert float to a string easily using str() function.

Which function will take a string value and convert it to a floating point number if possible?

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.


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)

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

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 (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}"

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


Python 3.6

Just to make it clear, you can use f-string formatting. This has almost the same syntax as the format method, but make it a bit nicer.

Example:

print(f'{numvar:.9f}')

More reading about the new f string:

  • What's new in Python 3.6 (same link as above)
  • PEP official documentation
  • Python official documentation
  • Really good blog post - talks about performance too

Here is a diagram of the execution times of the various tested methods (from last link above):

execution times


Using round:

>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'

In case the precision is not known until runtime, this other formatting option is useful:

>>> n = 9
>>> '%.*f' % (n, numvar)
'135.123456789'

It's not print that does the formatting, It's a property of strings, so you can just use

newstring = "%.9f" % numvar

To set precision with 9 digits, get:

print "%.9f" % numvar

Return precision with 2 digits:

print "%.2f" % numvar 

Return precision with 2 digits and float converted value:

numvar = 4.2345
print float("%.2f" % numvar)