Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a float to a string without rounding it

I'm making a program that, for reasons not needed to be explained, requires a float to be converted into a string to be counted with len(). However, str(float(x)) results in x being rounded when converted to a string, which throws the entire thing off. Does anyone know of a fix for it? Here's the code being used if you want to know:

len(str(float(x)/3)) 
like image 767
Galileo Avatar asked Aug 23 '09 02:08

Galileo


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.

Can you convert a float to a string in Python?

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

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.

How do you print a float without scientific notation?

Within a given f-string, you can use the {...:f} format specifier to tell Python to use floating point notation for the number preceding the :f suffix. Thus, to print the number my_float = 0.00001 non-scientifically, use the expression print(f'{my_float:f}') .


1 Answers

Some form of rounding is often unavoidable when dealing with floating point numbers. This is because numbers that you can express exactly in base 10 cannot always be expressed exactly in base 2 (which your computer uses).

For example:

>>> .1 0.10000000000000001 

In this case, you're seeing .1 converted to a string using repr:

>>> repr(.1) '0.10000000000000001' 

I believe python chops off the last few digits when you use str() in order to work around this problem, but it's a partial workaround that doesn't substitute for understanding what's going on.

>>> str(.1) '0.1' 

I'm not sure exactly what problems "rounding" is causing you. Perhaps you would do better with string formatting as a way to more precisely control your output?

e.g.

>>> '%.5f' % .1 '0.10000' >>> '%.5f' % .12345678 '0.12346' 

Documentation here.

like image 192
John Fouhy Avatar answered Sep 28 '22 01:09

John Fouhy