How to Truncate Float to 2 Decimal Places in Python
To truncate a float to 2 decimal places in Python, you can multiply the number by 100, use
math.trunc() to remove extra decimals, then divide by 100. Alternatively, convert the float to a string with slicing or use decimal.Decimal for precise control.Syntax
Here is the basic syntax to truncate a float to 2 decimal places using math.trunc():
import math: imports the math module.math.trunc(value * 100) / 100: multiplies the float by 100, truncates the decimal part, then divides back by 100.
python
import math truncated_value = math.trunc(your_float * 100) / 100
Example
This example shows how to truncate the float 3.14159 to 2 decimal places using math.trunc() and also using string slicing.
python
import math number = 3.14159 # Using math.trunc truncated = math.trunc(number * 100) / 100 print(truncated) # Output: 3.14 # Using string slicing str_num = str(number) if '.' in str_num: integer_part, decimal_part = str_num.split('.') truncated_str = integer_part + '.' + decimal_part[:2] truncated_float = float(truncated_str) else: truncated_float = float(str_num) print(truncated_float) # Output: 3.14
Output
3.14
3.14
Common Pitfalls
Many people try to use round() to truncate, but round() rounds the number instead of truncating it. Also, converting floats to strings and back can cause errors if not handled carefully.
Using format() or f-strings only formats the output but does not change the actual float value.
python
import math number = 3.149 # Wrong: round() rounds instead of truncates print(round(number, 2)) # Output: 3.15 (not truncated) # Right: truncation truncated = math.trunc(number * 100) / 100 print(truncated) # Output: 3.14
Output
3.15
3.14
Quick Reference
| Method | Description | Example Output for 3.149 |
|---|---|---|
| math.trunc() | Truncates by removing decimals after multiplying | 3.14 |
| String slicing | Convert to string and cut decimals | 3.14 |
| round() | Rounds number, not truncates | 3.15 |
| format()/f-string | Formats output, does not change value | '3.15' as string |
Key Takeaways
Use math.trunc(value * 100) / 100 to truncate a float to 2 decimals.
round() rounds numbers and does not truncate.
String slicing can truncate but requires careful conversion.
Formatting with f-strings changes display, not the float value.
Truncation removes decimals without rounding up.