Back to Explore
GuideVibeFix editorialUpdated Nov 20, 2026

Don't let 0.1 + 0.2 break your bill: JavaScript numbers and Math, explained plainly

Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.

Real photo: a Casio scientific calculator on a wooden desk showing 123456789 + 987654321 = 1111111110, beside handwritten math notebooks, a pen, a mug, and a laptop edge

Let me set the boundary first. This site already has quite a few JavaScript basics guides: array methods covered lists, string methods covered text, date handling covered time, regular expressions covered patterns, and destructuring, class and prototypes, closures, the event loop, modules, Fetch, the DOM, and localStorage each have their own guide. This one does not repeat them. It covers one thing only: numbers themselves. Adding up a bill, applying a discount, picking something at random, rounding to two decimals — all of that runs on the two built-in objects Number and Math. The running example is the same fictional practice project as the earlier guides: the Greenstone Cafe order page, a small web tool for a street-corner cafe. Earlier guides covered how its order page looks and how it lays out; this one covers how it does the math: two lattes plus a cake, how much after a discount, a daily special picked at random, how many decimals to show. Everything in this article that uses the cafe as an example — the operations, the code, and the numbers — is made up to explain the method. It is not a real record. All syntax and behavior of numbers and Math comes from three official MDN documents: "Basic math in JavaScript — numbers and operators", "Math", and "Number". The sources are listed in this article's meta information and evidence record. After reading it, you should be able to do four things: know what a number really is in JavaScript, understand why 0.1 + 0.2 is not 0.3, turn strings from inputs into numbers reliably, and know which method to use for rounding, random picks, and formatting. This guide does not cover BigInt in full, number math inside Date, or bitwise operations and typed arrays; it only mentions them where they matter.

Step 1: There is only one number type — integers and decimals are both Number

MDN's Learn article starts with a fact that comes as a relief to beginners: JavaScript has only one data type for numbers. Integers and decimals are both Number. Write 5 and it is a Number; write 6.667 and it is also a Number; typeof returns "number" for both. That is different from many languages, where integers and decimals are two types and you have to keep converting between them. The same Learn article adds that JavaScript does have a second number type, BigInt, for very, very large integers — but this guide only deals with Number, and BigInt is a topic for another day. MDN's Number reference page says it even more firmly: a number literal like 37 in code is a floating-point value, not an integer. In everyday use there is no separate integer type. Why is that? Because Number is a double-precision 64-bit binary format, IEEE 754: 64 bits, with 1 bit for the sign, 11 bits for the exponent, and 52 bits for the mantissa. That sounds like a hardware lesson, but the practical conclusion is simple: since there is only one type, you can write 10 and 10.5 with the same rules and add, subtract, multiply, and divide them directly, with no conversion first. On the cafe order page, the quantity is the integer 2 and the unit price is the decimal 19.9, and 2 * 19.9 just works — no need to convert one into the other. But sharing one representation has a price: integers and decimals share the same precision ceiling, and that ceiling is what the next step is about, 0.1 + 0.2. Remember the judgment from this step: when typeof returns "number", it only says the value is a number. It does not say whether it is an integer or a decimal, and it says nothing about how precise it is.

Step 2: Do the sum first — why 0.1 + 0.2 is not 0.3

This is the most famous trap in JavaScript, and the first time many beginners doubt their own sanity: type 0.1 + 0.2 into the console and you get 0.30000000000000004, not 0.3. MDN's Number reference page explains why in its IEEE 754 section: the mantissa has only 52 bits, so the precision is about 15 to 17 significant decimal digits, and arithmetic beyond that level gets rounded. 0.1 and 0.2 look clean in decimal, but in binary they are repeating fractions that 64 bits cannot hold exactly, so each is stored as the closest approximation, and adding two approximations exposes the error. This is not a JavaScript bug: double in Java and C# uses the same format and behaves the same way. The same page offers more evidence: 0.1 + 0.7 gives 0.7999999999999999, and comparing it with 0.8 using strict equality returns false. One more small number shows how tiny the error is: 0.1 + 0.2 - 0.3 equals 5.551115123125783e-17, which is smaller than Number.EPSILON (2.220446049250313e-16, the smallest interval between two representable numbers). So the error is real, but it only shows up at the 17th decimal place. On the cafe order page, the error is usually invisible: a coffee at 19.9, two of them at 39.8 — those numbers happen to come out clean. But as soon as prices combine 0.1, 0.2, or 0.7, the bill can grow an extra 0.00000000000000004. The fix is not to memorize binary. It is the approach in the next step: count money in integers. Remember the conclusion: floating-point error is not a random glitch. It is built into Number, and any language using IEEE 754 has it. To judge whether code is trustworthy, check whether it has accounted for the error.

Step 3: Do not add money in decimals — count in cents instead

Since adding decimals carries error, the most reliable way to handle money is to keep decimals out of the calculation entirely: convert dollars to cents, do everything in integers, and convert back to dollars only for display. The cafe example is direct: one latte costs 19.9, written as 1990 cents; two lattes are 1990 * 2 = 3980 cents, and dividing by 100 for display gives 39.8. Why go around in a circle? Because 19.9 * 100 in JavaScript equals 1989.9999999999998, not 1990 — so even the dollars-to-cents step needs rounding first: Math.round(19.9 * 100) equals 1990, a clean integer. The full flow is three lines: when a price enters the page, multiply by 100 and Math.round it into integer cents; do subtotals, discounts, and spend-and-save reductions entirely in integer cents; only at display time, divide by 100 and fix it to two decimals with toFixed(2). A spend-and-save example works the same way: an order of 3980 cents, spend 3000 and save 500, gives 3980 - 500 = 3480 cents, displayed as 34.80 — no decimal ever entered the calculation. The bad example is worth seeing too: 19.9 + 19.9 giving 39.8 is luck, but 0.1 + 0.7 gives 0.7999999999999999, and if you compare that with 0.8 using strict equality, the condition never passes, so a discount check can silently fail. One matching habit: when comparing two amounts for equality, do not write a === b. Write Math.abs(a - b) < Number.EPSILON instead, and treat them as equal when the difference is smaller than the smallest representable interval. The judgment in this step is simple: whenever a calculation ends up as money, ask "did a decimal enter the calculation?" If it did, switch to cents.

Step 4: Numbers have four written forms, and all of them must be the same value

MDN's Number reference page opens by listing the ways to write a number literal, and the point is that the writing can be fancy but the value must be identical. Decimal is the most common: 255 is 255, and 255.0 is the same number as 255, so 255 === 255.0 returns true. Hexadecimal starts with 0x, and 255 === 0xff returns true. Binary starts with 0b, and 255 === 0b11111111 returns true. Exponential notation uses e, and 255 === 0.255e3 returns true, because 0.255 times 10 to the power of 3 is 255. On the cafe order page, each form has its use: item numbers use decimal 12; color values are already hexadecimal in CSS, and in JavaScript 0xff is the same as 255; when combining permission bits or on-off switches, binary 0b11111111 shows at a glance that all 8 switches are on; and exponential notation saves counting zeros for very large numbers. But there are two lines not to cross. First, do not put quotes around a number in code: quotes turn it into a string, and "74" and 74 are two different types — the next step covers what happens when you add them. Second, octal is a trap in strict mode: MDN states clearly that a leading 0 in a string being converted to a number does not make it octal, but writing a number literal like 0123 directly in code is rejected in strict mode, so do not write numbers that way. The check for this step is easy: if you are unsure whether two written forms are the same value, compare them with strict equality in the console. 255 === 0xff is a ready-made touchstone.

Step 5: What comes out of an input is always a string — convert it to a number before calculating

The most common bug on an order page hides in the input box: the user types 3 into the quantity field, and JavaScript receives the string "3", not the number 3. MDN's Learn article demonstrates it with a clean example: let myNumber = "74", then myNumber += 3 gives "743", not 77, because the plus sign next to a string becomes concatenation, and 3 is pasted onto 74 as text. To get 77, convert first: myNumber = Number(myNumber) + 3. Number() does exactly that job: Number("123") returns the number 123, and Number("123") === 123 returns true; when the value cannot be converted, it returns NaN — Number("unicorn") is NaN, and Number(undefined) is NaN too. MDN's Number reference page lays out the whole conversion table: undefined becomes NaN, null becomes 0, true becomes 1 and false becomes 0, an empty string or a string of only whitespace becomes 0, "Infinity" and "-Infinity" are recognized, a leading sign is allowed, but numeric separators are not. Two details are easy to miss. First, Number("0x11") equals 17 — hexadecimal strings are recognized; Number("0b11") equals 3 and Number("0o11") equals 9, so binary and octal strings are recognized too. Second, Number("100a") is NaN: one stray letter in the string fails the whole conversion, unlike parseInt, which reads halfway and stops — that comes below. The rule for the cafe order page should be: any number coming from an input box, the address bar, or an API goes through Number() before it enters a calculation, and right after converting, check whether it is NaN. The check is Number.isNaN(), and the next step explains how it differs from the global isNaN. There is an equivalent shorthand: unary plus, +x, performs the same conversion, so +"74" equals 74. It is shorter to write, but less readable than Number(), and mixing two spellings in one team makes code harder to follow. Pick one and use it consistently.

Step 6: NaN and Infinity — two numbers that are not numbers

Number has two special values that look like numbers but really mean "this calculation could not be done". The first is NaN, short for Not-a-Number, which MDN's Number reference page lists as Number.NaN. Number("unicorn") is NaN, 0 divided by 0 is NaN, and any number calculated together with NaN stays NaN. The strangest thing about NaN is that it is not equal to itself: NaN === NaN returns false. So never test for NaN with x === NaN — that line is always false. The correct tool is Number.isNaN(), which returns true only when the value really is NaN. MDN does not go into the global isNaN() in detail, but one judgment belongs here: the global isNaN("hello") returns true, because it first converts the string to a number before testing, while Number.isNaN("hello") returns false, because it does no conversion and only recognizes genuine NaN. On the order page, use only Number.isNaN(). The global one is too eager and counts a non-numeric string as NaN. The second special value is Infinity. 1 divided by 0 equals Infinity, -1 divided by 0 equals -Infinity, and a number larger than Number.MAX_VALUE also becomes Infinity — Number.MAX_VALUE * 2 is Infinity. MAX_VALUE is the largest positive number Number can hold, about 1.7976931348623157e+308; there is no need to memorize it, only to know the ceiling exists. To test whether a value is a finite number, use Number.isFinite(); to test whether it is an integer, use Number.isInteger(), which returns true for both 5 and 5.0, because they are the same value in the first place. The checklist for this step is short: whenever user input is involved in a division, ask first whether the denominator can be 0; whenever Number() returns a result, ask whether it is NaN. Check both, and the bill will never turn mysteriously into NaN or Infinity.

Step 7: Safe integers — beyond 9007199254740991, stop trusting the number

The integers Number can represent exactly are not infinite. MDN's Number reference page states the limit plainly: only integers from -(2 to the power of 53 minus 1) to 2 to the power of 53 minus 1 can be represented without losing precision, and those two endpoints are Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER. The maximum is 9007199254740991. Beyond that range, integers start sticking together: 9007199254740991 plus 1 equals 9007199254740992, and plus 2 also equals 9007199254740992 — two different additions landing on the same result. The cause is again the 52-bit mantissa: once integers pass 53 binary digits, neighboring representable numbers are more than 1 apart, and the integers in between simply cannot be stored. The cafe order page will not normally meet numbers this large — a single order is a few thousand cents, a day is a few tens of thousands, far from 9 quadrillion. But two situations demand caution. First, order numbers or snowflake-style long IDs: the number itself is already beyond the safe range, so adding or subtracting 1 from it as a Number can quietly go wrong. Second, large integers arriving as JSON: MDN warns explicitly that the JSON parser corrupts integer values outside this range when it coerces them to Number, and the workaround is to send them as strings instead. The checking tool is Number.isSafeInteger(), which returns true when the value is an integer between -(2 to the power of 53 minus 1) and 2 to the power of 53 minus 1. One constant is easy to confuse with it: Number.MIN_VALUE is not the most negative number, but the positive number closest to zero. Do not mix it up with MIN_SAFE_INTEGER. The judgment here is simple: everyday numbers like amounts, cents, and quantities can use Number freely; but for any long number used as an identifier, first ask whether it exceeds 9007199254740991 — if it does, use a string, or leave it to BigInt.

Step 8: Four ways to round — floor, ceil, round, and trunc each do their own job

Rounding is a daily operation on the order page: rounding down to reach a discount threshold, rounding up for head counts, rounding to the nearest for displayed amounts. MDN's Math reference page lists the four methods side by side, and their definitions separate them in one sentence each: Math.floor() returns the largest integer less than or equal to the input — rounding down; Math.ceil() returns the smallest integer greater than or equal to the input — rounding up; Math.round() returns the value rounded to the nearest integer; Math.trunc() removes the fractional digits and returns the integer portion. Definitions alone are easy to confuse, so run -1.5 and 2.5 through all four: for -1.5, floor is -2, ceil is -1, round is -1, and trunc is -1; for 2.5, floor is 2, ceil is 3, round is 3, and trunc is 2. One more: for -2.5, round is -2, because a .5 rounds toward positive infinity, and -2.5 is on the -2 side of that rule. Cafe examples make it stick: three people split a 100-cent order, 33.333 cents each, and round shows 33; a table needs 7 chairs at 2 people per chair, 7 divided by 2 is 3.5 tables, and ceil makes it 4 tables, because half a table leaves people with nowhere to sit; a spend-3000-save-500 deal on an order of 2999.6 cents floors to 2999, one cent short of the threshold, and the customer will come asking why the discount did not apply; trunc fits "integer portion only" cases, like truncating 19.9 to 19 — but note that for negative numbers it cuts toward zero, not downward. A common beginner mistake is assuming round is banker's rounding or round-half-to-even. It is not: round sends .5 toward positive infinity, so 2.5 becomes 3 and -2.5 becomes -2. Before rounding, decide what you need: "is it enough" calls for ceil, "cut the fraction off" calls for trunc, "closest" calls for round, and plain rounding down is floor.

Step 9: Random numbers — Math.random() never reaches 1

The daily special changes every day, and draws, shuffles, and random recommendations all need random numbers. MDN's Math reference page defines it in one sentence: Math.random() returns a pseudo-random number between 0 and 1. The key is in the word "between": it can equal 0, but it never reaches 1 — the interval is [0, 1), closed on the left and open on the right. That detail decides how to write a random integer, and MDN gives the standard pattern on the same page: function random(min, max) { const num = Math.floor(Math.random() * (max - min + 1)) + min; return num; }, and random(1, 10) picks an integer evenly between 1 and 10. The + 1 in the formula is the easiest part to drop. Without it, Math.floor(Math.random() * 10) + 1 still covers 1 to 10 correctly — Math.random() * 10 sits in [0, 10), floor gives 0 to 9, plus 1 gives 1 to 10. But write it as Math.floor(Math.random() * (10 - 1)) + 1 and the range becomes 1 to 9, with 10 never drawn. A more common mistake is Math.round(Math.random() * 10): round gives 0 and 10 only half the probability of the middle numbers, so the draw is uneven. The cafe example: the menu has 8 dishes, and the daily special picks one — random(1, 8) works, and so does Math.floor(Math.random() * 8), which returns 0 to 7, exactly matching array indexes 0 to 7. Two more warnings: first, Math.random() is a pseudo-random number — MDN's wording is pseudo-random — so do not use it for passwords, prize draws, or anything that must be unpredictable; those need a dedicated cryptographic random source. Second, the precision of many Math functions is implementation-dependent, as MDN notes at the top of the Math reference page: the same engine on a different operating system or architecture can give a different result in the last digit, so do not use strict equality to test Math.sin or Math.log results.

Step 10: The Math toolbox — max, min, and trigonometry each have their own job

Math is not a constructor. You cannot write new Math(), and you cannot call the Math object as a function. All of its properties and methods are static — just write Math.something. MDN's Math reference page lists eight constants and more than thirty methods, and beginners do not need to memorize all of them; the common groups are enough. The first group is constants: Math.PI is pi, about 3.14159; Math.E is Euler's number, about 2.718; Math.SQRT2 is the square root of 2, about 1.414; Math.SQRT1_2 is the square root of one half, about 0.707; and LN2, LN10, LOG2E, and LOG10E are logarithm constants that are rarely needed — knowing they exist is enough. The second group compares values: Math.max() returns the largest of zero or more numbers, Math.min() the smallest — on the order page, use them to take the best discount or the lowest price directly; Math.abs() returns the absolute value, so price differences need no sign check of your own; Math.sign() returns the sign: 1 for positive, -1 for negative, 0 for zero. The third group is powers and roots: Math.pow(7, 3) equals 343, the same as 7 ** 3 — MDN's Learn article states the two are equivalent; Math.sqrt() takes a square root, Math.cbrt() a cube root, and Math.hypot(3, 4) equals 5, computing the square root of the sum of squares — 3-4-5 in one step. The fourth group is trigonometry: sin, cos, tan, asin, acos, atan, and atan2, and MDN states clearly that they expect and return angles in radians, not degrees. Converting between the two needs two small helper functions, and MDN provides them on the same page: degToRad is degrees * (Math.PI / 180), and radToDeg is rad / (Math.PI / 180). The document's example calculates the height of an equilateral triangle: side length 100, half of it 50, angle 60 degrees, and 50 * Math.tan(degToRad(60)) equals 86.60254037844383 — check it: tan(60 degrees) is the square root of 3, about 1.7320508075688772, times 50 gives exactly that number. The cafe order page has no use for trigonometry, but the moment you draw on Canvas, build a prize wheel, or draw a circular progress ring, radians will come looking for you — save degToRad now. The logarithm group — log, log10, log2, exp, expm1 — is rarely needed day to day; knowing Math.log() is the natural logarithm is enough, and the rest can wait until a real use appears.

Step 11: Showing numbers to people — toFixed, toLocaleString, and a chart of mistakes

Calculated numbers eventually have to be shown to people, and the way you display them should stay separate from the way you calculate them. MDN's Learn article gives the most common display method: (1.7665849587).toFixed(2) gives "1.77", fixed to two decimal places. But here is the easiest trap for beginners: toFixed() returns a string, not a number. Add 1 to "1.77" and you get "1.771", not 2.77, because the plus sign next to a string becomes concatenation again. The correct flow is: do all calculating with numbers, call toFixed() only at the moment of display, and put the result straight into the page — never calculate with it again. MDN's Number reference page lists three more formatting methods: toPrecision() takes a number of significant digits, so (123.456).toPrecision(4) gives "123.5"; toExponential() writes scientific notation, so (123456).toExponential(2) gives "1.23e+5"; and toString() takes a radix, so (255).toString(16) gives "ff" and (255).toString(2) gives "11111111", which is handy when debugging in hexadecimal or binary. There is also toLocaleString(), which adds thousands separators and locale formatting: (1234567.89).toLocaleString('en-US') gives "1,234,567.89", and in a Chinese locale (1234567).toLocaleString('zh-CN') gives "1,234,567" — a bill total shown this way is far easier to read than a bare string of digits. The complete pipeline for the cafe order page should be: when a price enters the page, multiply by 100 and Math.round it into integer cents; do subtotals, discounts, and spend-and-save reductions entirely in integer cents; at display time, divide by 100 and fix to two decimals with toFixed(2), or add thousands separators with toLocaleString(). The chart below shows a fictional breakdown of 100 number mistakes in one month on the Greenstone Cafe order page. The numbers are invented examples, mapped against the traps in the ten steps above: string concatenation 18 times, the most common; toFixed used as a number 16 times; floating-point error and random-number overflow 15 times each; wrong rounding choice 12 times; parseInt traps 10 times; division by zero turning into Infinity 8 times; exceeding the safe integer range 6 times. 18 + 16 + 15 + 15 + 12 + 10 + 8 + 6 = 100, and the account balances.

Bar chart: fictional breakdown of 100 number mistakes in one month on the Greenstone Cafe order page, with string concatenation at 18 the largest group

Step 12: A pre-launch checklist — five questions that keep numbers correct

Once the order page's billing logic is written, run through these five questions before launch. First, were the input numbers converted? Any number from an input box, the address bar, or an API goes through Number() before calculating, and the result gets checked with Number.isNaN() — values that cannot convert must never reach the bill. Second, is money counted in cents? Multiply the price by 100, Math.round it into integer cents, do all arithmetic in integers, and divide by 100 only for display, so floating-point error never enters the calculation. Third, was the denominator checked before dividing? It can be 0, or the user may have left it empty: 1 divided by 0 is Infinity, 0 divided by 0 is NaN, and both make the bill display look strange — block them before calculating. Fourth, was the right rounding method chosen? "Is it enough" calls for ceil, "closest" calls for round, "cut the fraction off" calls for trunc, and plain rounding down is floor — do not pick by feel. Fifth, is the random-number formula right? Math.floor(Math.random() * (max - min + 1)) + min — do not drop the + 1, and do not use round to pick a random integer, or the daily special will never land on dish 10 because the formula is wrong. After those five checks, look back at the three MDN documents: the Learn article covers basic operations and operator precedence, the Math reference is the toolbox list, and the Number reference is the manual for the type itself. They have different jobs, so do not knock on the wrong door: if you do not know what a method is called, go to the Math reference; if you do not know what limits a number has, go to the Number reference; if you do not know which operator runs first, go to the precedence section of the Learn article. One last note: BigInt, numbers inside Date, bitwise operations, and typed arrays were left out of this guide, and each has its own traps — when you really need one of them, read the matching MDN document first instead of writing from memory.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: over-the-shoulder view of a man typing CSS code on a laptop, selectors visible on screen, with coffee, glasses, and a phone on the desk
Guide
Getting styles onto the right elements: CSS selectors, explained plainly

A selector is the first part of a rule: it decides who the styles land on. This guide follows MDN's Basic CSS selectors, Attribute selectors, and Pseudo-classes and pseudo-elements: type, class, ID, selector lists, universal, attribute selectors, pseudo-classes, pseudo-elements, chaining them together, plus a checklist for when a style does not show up.

Tool TipsFrontend EngineeringAI Coding
Real photo: a hand holding a stylus draws a colorful picture on a tablet, with a paint palette and brushes on the desk
Guide
Drawing without images: Canvas basics, explained plainly

No image files, no library: the order page's weekly bar chart and smiley face are drawn live with Canvas. This guide follows MDN's Canvas tutorial — Basic usage, Drawing shapes, and Applying styles and colors: the 300×150 default, the top-left origin, fillRect and strokeRect, the beginPath-moveTo-lineTo-fill/stroke path pattern, arcs in radians, Bezier curves, fillStyle and strokeStyle, transparency, line styles, gradients, patterns, shadows, and redrawing for motion.

Tool TipsFrontend EngineeringAI Coding