Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a float number like 293.4662543 into 293.47 in python?

How to shorten the float result I got? I only need 2 digits after the dot. Sorry I really don't know how to explain this better in English...

Thanks

like image 296
Shane Avatar asked Oct 12 '10 12:10

Shane


People also ask

How do you change a float to a number in Python?

Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 . When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer.

How do I change the float format in Python?

Format float value using the round() Method in Python The round() is a built-in Python method that returns the floating-point number rounded off to the given digits after the decimal point. You can use the round() method to format the float value.

Can you turn a float into a string Python?

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

How do you round a float to two decimal places in Python?

Use the round() function to round a float to 2 decimals, e.g. result = round(4.5678, 2) . The round() function will return the number rounded to 2 digits precision after the decimal point.


1 Answers

From The Floating-Point Guide's Python cheat sheet:

"%.2f" % 1.2399 # returns "1.24" "%.3f" % 1.2399 # returns "1.240" "%.2f" % 1.2 # returns "1.20" 

Using round() is the wrong thing to do, because floats are binary fractions which cannot represent decimal digits accurately.

If you need to do calculations with decimal digits, use the Decimal type in the decimal module.

like image 100
Michael Borgwardt Avatar answered Sep 21 '22 12:09

Michael Borgwardt