简体   繁体   中英

Is there a condition where the Math.ceil function in Javascript doesn't remove decimals from the output?

Is there a reason why some Javascript programmers use the following syntax to remove decimals?

Math.ceil(averageCost / 10) * 10;

Why wouldn't we just use Math.ceil? Doesn't it effectively do the same thing as the above? Is there a condition where Math.ceil doesn't work?

Initially I thought maybe this would eliminate string cases and return a zero, but in the following code, the results are NaN -

var name = "Gary";
console.log(Math.ceil(name / 10)); // NaN
console.log(Math.ceil(name)); // NaN

So I'm at a loss for why I'd see a division by 10 with a subsequent multiplication of 10.

The construct:

Math.ceil(averageCost / 10) * 10;

Does a form of rounding. It has the net effect of rounding up to the nearest whole number multiple of 10 . So:

11 => 20
20 => 20
21 => 30
11.99 => 20

Math.ceil(averageCost / 10) divides by 10 and rounds up to the nearest whole number (removing all decimal portions and all ones) and then the * 10 brings it back to the same numeric range it was originally in, but without the parts removed by the rounding.

Here's an example showing a number of results:

 const nums = [10,11,15,18,19,20,21,10.1,11.99,20.19]; for (let num of nums) { let result = Math.ceil(num/10) * 10; console.log("Input: ", num, ", Output: ", result); }


Why wouldn't we just use Math.ceil? Doesn't it effectively do the same thing as the above? Is there a condition where Math.ceil doesn't work?

This combination rounds up to the nearest whole number multiple of 10 whereas Math.ceil() only rounds up to the nearest whole number. So, the two cases you ask about have different uses. Use the one that accomplishes what you want to accomplish. For a number where the integer portion is already a power of ten such as 10.3, the two would have the same output, but for any other number such as 11.3, the two would not have the same output.

Math.ceil(11.3) === 11
(Math.ceil(11.3 / 10) * 10) === 20

Is there a condition where the Math.ceil() function in Javascript doesn't remove decimals from the output?

No. There is not. It's whole function is to round up to the nearest whole number (thus removing any decimal fraction from the number).

So I'm at a loss for why I'd see a division by 10 with a subsequent multiplication of 10.

To round up to the nearest whole number multiple of 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM