Limiting Floats to Two Decimal Points

How to display a float with two decimal places?

You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.

How to round to 2 decimals with Python?

You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.

In your case, it would be:

answer = str(round(answer, 2))

Limit decimal points in a float

You are looking for

x = math.pi
print(f"{x:.2f}")

This is called an f-string. It formats x as a string of a floating point number (f) with 2 decimal places (.2f).

Python3.4 limiting floats to two decimal points

You can convert to string and slice then convert to float :

>>> num=1.2377
>>> float(str(num)[:-2])
1.23

read more about Floating Point Arithmetic: Issues and Limitations

How to convert all floats to two decimal places regardless of number of decimal places float has without repeating convert code?

The bad news is: there is no "float" with "two decimal places".

Floating point numbers are represented internally with a fixed number of digits in base 2. https://floating-point-gui.de/basic/ .

And these are both efficient and accurate enough for almost all calculations we perform with any modern program.

What we normally want is that the human-readable text representation of a number, in all outputs of a program, shows only two digits. And this is controlled at wherever your program is either writting the value to a text file, to the screen, or rendering it to an HTML template (which is "writing it to a text file", again).

So, it happens that the same syntaxes that will convert a number to text, embedded in another string, allows additionally to control the exact output of the number. You put as an example print(f"{9.9:.2f}"). The only thing that looks impractical there is due to you hardcoding your number along with its conversion. Typically, the number will be in a variable.

Them, all you have to do is writting, wherever you output the number:

print(f"The value is: {myvar:.02f}")

instead of

print(f"The value is: {myvar}")

Or in whatever function you are calling that will need the rendered version of the number instead of print. Notice that the use of the word "rendered" here is deliberate: while your program is running, the number is stored in an efficient way in memory, directly usable by the CPU, that is not human readable. At any point you want to "see" the number, you have to convert it into text. It is just that some calls to it implicitly, like print(myvar). Then, just resort to explicitly converting it in these places - `print(f"{myvar:.02f}").

really having 2 decimal places in memory

If you use decimal.Decimal, then yes, there are ways to keep the internal representation of the number with 2 decimal digits,
but them, instead of just converting the number on output, you must convert it into a "2 decimal place" value on all inputs as well

That means that whenever ingesting a number into your program, be it typed by the user, read from a binary file or database, or received via wire from a sensor, you have to apply a similar transform to the one used in the output as detailed above. More precisely: you convert your float to a properly formatted string, and then convert that to a decimal.Decimal.

And this will prevent your program of accumulating errors due to base conversion, but you will still need to force the format to 2 decimal places on every output, just like above.

How to round each item in a list of floats to 2 decimal places?

"%.2f" does not return a clean float. It returns a string representing this float with two decimals.

my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
my_formatted_list = [ '%.2f' % elem for elem in my_list ]

returns:

['0.30', '0.50', '0.20']

Also, don't call your variable list. This is a reserved word for list creation. Use some other name, for example my_list.

If you want to obtain [0.30, 0.5, 0.20] (or at least the floats that are the closest possible), you can try this:

my_rounded_list = [ round(elem, 2) for elem in my_list ]

returns:

[0.29999999999999999, 0.5, 0.20000000000000001]

Python 3 Float Decimal Points/Precision

In a word, you can't.

3.65 cannot be represented exactly as a float. The number that you're getting is the nearest number to 3.65 that has an exact float representation.

The difference between (older?) Python 2 and 3 is purely due to the default formatting.

I am seeing the following both in Python 2.7.3 and 3.3.0:

In [1]: 3.65
Out[1]: 3.65

In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'

For an exact decimal datatype, see decimal.Decimal.



Related Topics



Leave a reply



Submit