node.js - Is there a condition where the Math.ceil function in Javascript doesn't remove decimals from the output? - Stack Overflow
javascript - Math.round vs. math.ceil yields unexpected results - Stack Overflow
math - javascript - ceiling of a dollar amount - Stack Overflow
Why not always use Math.round instead of Math.floor?
Well, they are two different functions, with two different uses. Math.floor() always rounds down to the nearest integer, while Math.round() will round up or down depending on what side of .5 the number falls on. So, the basic answer is that you use which one gets the result you expect.
When it comes to generating random numbers though, Math.floor() has a more even distribution than Math.round(). If you want to generate a random number between 0 and 2, take the following examples:
Math.floor(Math.random() * 3). Here, 0-0.999999 will give you 0, 1.0 to 1.999999 will give you 1, and 2.0 to 2.999999 will give you 2. Every number has a 33% chance of being the result.
Math.round(Math.random() * 2). Here, 0-0.499999 will give you 0, 0.5 to 1.499999 will give you 1, and 1.5 to 1.999999 will give you 2. Note that the range of numbers that lead to a 1 is twice as big as those that lead to 0 or 1. That is 25% chance of 0, 50% chance of 1, and 25% chance of 2.
Videos
You can't do it in a simple way.
The problem is that the computer stores numbers in base 2, and has a finite precision. Then, your 8.88 becomes
8.88000000000000078159700933611020445823669433593750
According to your rules, it is rounded up to 8.89.
A solution could be multiplying your quantities by 100 (in the source code, not using JS), and divide them by 100 at the end.
var fieldVal100 = 888; // 8.88 * 100
fieldVal100 = Math.ceil(fieldVal100);
var fieldVal = fieldVal100 / 100; // 8.88
var fieldVal100 = 50000/3; // 500/3 * 100
fieldVal100 = Math.ceil(fieldVal100);
var fieldVal = fieldVal100 / 100; // 166.67
var fieldVal100 = 50000/6.95; // 500/6.95 * 100
fieldVal100 = Math.ceil(fieldVal100);
var fieldVal = fieldVal100 / 100; // 71.95
Another solution would be storing the numbers as strings instead of numbers, and use some library which operates those strings in base 10.
If you want to round up use ceil() and not round():
fieldVal = Math.ceil(fieldVal * 100) / 100;
If you round 7194.2 you will get 7194 and not 7195, hence leading to 71.94.
The reason why 8.88 * 100 is going to 8.89 is because the way computers store decimal numbers. Because they cannot represent all possible decimals they are approximated to a degree. So 8.88 * 100 = 888.0000000000001, which using ceil leads to 889.
num = Math.ceil(num * 100) / 100;
Though, due to the way floats are represented, you may not get a clean number that's to two decimal places. For display purposes, always do num.toFixed(2).
Actually I don't think you want to represent dollar amounts as float, due to the same reason cited by Box9. For example, 0.1*3 != 0.3 in my browser. It's better to represent them as integers (e.g. cents).