In Turn Numeric Text Into Numbers, you converted gear weights like "2.5" into real numbers. In When Numbers Surprise You, you saw that 0.1 + 0.2 leaves a tiny leftover behind the decimal point. Both lessons leave you with numbers that have decimals, and many everyday questions call for a whole number instead.
Whole numbers don’t all come from the same kind of rounding, though. If you’re packing snack bars into boxes, a partly filled box still counts as a box. If you’re sharing bars among hikers, nobody gets a broken bar. And a weather report for a cold morning wants the nearest whole degree, even below zero.
In this lesson, you’ll learn four rounding tools and pick the one each story needs. You’ll also round to a number of decimal places and try a few more Math tools.
Meet the Math Toolbox
You’ve already used a tool with a dot in its name. Number.isNaN() is a function that JavaScript keeps under the name Number. In the same way, JavaScript keeps a set of number tools under the name Math, with a capital M. It’s always there, so you don’t need to set it up.
The first tool is Math.round(), which gives back the nearest whole number. Start the Node.js REPL by typing node in the integrated terminal, then try these lines:
> Math.round(2.7)
3
> Math.round(2.2)
2
You call a Math tool the same way you called Number(), with the value inside the parentheses. And just like Number(), it gives back a new number and leaves your variable alone. Store a weight and check it again after rounding:
> const bagKg = 1.6
undefined
> Math.round(bagKg)
2
> bagKg
1.6
The variable bagKg still holds 1.6. If you want to keep the rounded value, store it under a name of its own, such as const roundedKg = Math.round(bagKg);.
Round Down or Up to Fit the Story
Rounding to the nearest whole number isn’t always what a story needs. Say you’ve packed 20 snack bars for a group hike, and each box holds 6 bars. Dividing gives 3.333... boxes, but you can’t take a third of a box. Three boxes leave two bars behind, so you need a fourth box.
Math.ceil() rounds up to a whole number, like a ceiling above you. Math.floor() rounds down, like the floor below you. A number that’s already whole, like 3, stays the same with either one. Here’s how the snack bars work out, with Math.round() for comparison:
> Math.round(20 / 6)
3
> Math.ceil(20 / 6)
4