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
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.
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.
We can convert float to a string easily using str() function.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With