SoftwareSideHustles
How-To

How to Round to 2 Decimal Places (and Why 0.1 + 0.2 Isn't 0.3)

Why floating-point numbers give answers like 0.30000000000000004, how to round correctly in Python, JavaScript and Java, why round(2.675, 2) gives 2.67, and how to handle money safely.

By Software Side Hustles Editorial Team · Published · Updated · 4 min read

Quick answer: for display, format the number: f"{x:.2f}" in Python, x.toFixed(2) in JavaScript, String.format("%.2f", x) in Java. For money and anything that must add up exactly, do not use floats at all — use a decimal type (Decimal, BigDecimal) or store integer cents.

Why does 0.1 + 0.2 equal 0.30000000000000004?

python
>>> 0.1 + 0.2
0.30000000000000004

Almost every language stores floating-point numbers in IEEE 754 binary format. Binary can represent halves, quarters and eighths exactly, but not tenths — just as decimal cannot write one third exactly. So 0.1 is stored as the nearest representable binary value, a tiny bit off. Add two slightly-off numbers and the error becomes visible when printed.

This is not a bug in Python or JavaScript. You get the same result in Java, C#, Go, C++ and Rust. What changes between languages is only how many digits they print by default.

How do I round to 2 decimal places in Python?

python
x = 3.14159
round(x, 2) # 3.14 (a float)
f"{x:.2f}" # '3.14' (a string, for display)

Then the surprise:

python
round(2.675, 2) # 2.67, not 2.68

2.675 is actually stored as 2.67499999999999982236431605997495353221893310546875, so rounding correctly goes down. Python also uses round-half-to-even ("banker's rounding") for exact halves: round(0.5) is 0 and round(2.5) is 2, while round(3.5) is 4. It reduces bias when you round many values, but it surprises people who learnt "round half up" at school.

When you need decimal rules, use decimal:

python
from decimal import Decimal, ROUND_HALF_UP
Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) # Decimal('2.68')

Create the Decimal from a string. Decimal(2.675) copies the float's binary error and still rounds to 2.67.

How do I round to 2 decimal places in JavaScript?

javascript
const x = 3.14159;
x.toFixed(2); // "3.14" — a string
Number(x.toFixed(2)); // 3.14 — back to a number
Math.round(x * 100) / 100; // 3.14

Both approaches inherit binary errors:

javascript
(1.005).toFixed(2); // "1.00"
Math.round(1.005 * 100) / 100; // 1 — because 1.005 * 100 is 100.49999999999999

A common workaround nudges the value first — Math.round((1.005 + Number.EPSILON) * 100) / 100 gives 1.01 — but it is a patch, not a guarantee. For display, prefer Intl.NumberFormat, which also handles currency symbols and separators:

javascript
new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" }).format(1234.5);
// "£1,234.50"

How do I round to 2 decimal places in Java?

java
double x = 3.14159;
String shown = String.format("%.2f", x); // "3.14"
double r = Math.round(x * 100) / 100.0; // 3.14
BigDecimal money = new BigDecimal("2.675").setScale(2, RoundingMode.HALF_UP); // 2.68
BigDecimal fromDouble = BigDecimal.valueOf(2.675).setScale(2, RoundingMode.HALF_UP); // 2.68
BigDecimal exact = new BigDecimal(2.675).setScale(2, RoundingMode.HALF_UP); // 2.67!

BigDecimal.valueOf(double) goes via the double's shortest decimal string ("2.675"), while new BigDecimal(double) captures the exact binary value. Prefer the String constructor or valueOf. Also note that Java's Math.round rounds halves towards positive infinity: Math.round(2.5) is 3, but Math.round(-2.5) is -2.

How should I store and calculate money?

Pick one of two safe options:

  1. Integer minor units. Store 1999 pence instead of 19.99 pounds. Addition and comparison are exact. Convert to a decimal string only for display. Stripe and most payment APIs work this way.
  2. A decimal type. Python Decimal, Java BigDecimal, C# decimal, SQL NUMERIC(12, 2). These represent base-10 values exactly.

Never use FLOAT or DOUBLE columns for money. Totals drift by a penny, and reconciliation reports start failing at month end. Also decide when to round: rounding each line item and then summing can differ from summing and then rounding. Tax rules usually specify which one is required.

How do I compare floating-point numbers?

0.1 + 0.2 == 0.3 is False, so compare with a tolerance:

python
import math
math.isclose(0.1 + 0.2, 0.3) # True

In JavaScript: Math.abs(a - b) < Number.EPSILON * Math.max(1, Math.abs(a), Math.abs(b)). In tests, use your framework's approximate assertion — pytest.approx, Jest's toBeCloseTo, JUnit's assertEquals(expected, actual, delta). See equality operators explained for the broader picture.

Rounding modes in one table

Mode2.5 →-2.5 →Used by
Half to even2-2Python round, Decimal default, IEEE 754 default
Half up (away from zero)3-3Most school arithmetic, ROUND_HALF_UP
Half towards +∞3-2Java Math.round, JavaScript Math.round
Truncate2-2int() in Python, Math.trunc in JavaScript

Frequently asked questions

Why does toFixed return a string?

Because its job is formatting for display. Wrap it in Number() if you need a number, but remember the result is still a binary float.

How do I always round up to 2 decimal places?

Use ceiling on scaled values: math.ceil(x * 100) / 100 in Python or Math.ceil(x * 100) / 100 in JavaScript, or ROUND_CEILING with Decimal. Watch out — Math.ceil(1.1 * 100) is 111, because 1.1 * 100 is 110.00000000000001. A decimal type avoids this.

How do I remove trailing zeros?

In Python, f"{x:g}" or format(Decimal(s).normalize(), "f"). In JavaScript, Number(x.toFixed(2)).toString() drops trailing zeros.

Is this problem specific to JavaScript?

No. Any language using IEEE 754 doubles shows the same behaviour; some just print fewer digits by default.

Where this skill pays off

Money calculated with floats is one of the most common defects in AI-written code, and it often passes simple tests. Our free invoice rounding exercise asks you to judge two solutions to exactly this problem. Catching issues like this is what AI code-evaluation work pays for — see how to evaluate AI-generated code.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy