According to the question, this was the desired result:
- The value
12.999must be displayed as
- The value
14must be displayed as
The developer.mozilla.org page gives a thorough example of how to perform decimal rounding correctly, avoiding any rounding errors in the process. For this question, however, a simple multiplication-division pair is surely good enough:
// Step by step var multiplied = value * 100; var truncated = Math.floor(multiplied); var divided = truncated * 0.01; var output = divided.toFixed(2); // One-liner version var output = (Math.floor(value * 100) * 0.01).toFixed(2);
The above code performs the following steps, in order:
- Value is multiplied by 100
12.999 => 1299.9
14 => 1400
- Value is truncated using the
1299.9 => 1299
1400 => 1400
- Value is multiplied by 0.01
1299 => 12.99
1400 => 14
- Value is formatted for printing using two decimal places using the
12.99 => "12.99"
14 => "14.00"
Most languages do have functions called
floor or similar ones, but almost all of them round to the nearest integer, so the
multiply-round-divide chain (or divide-round-multiply for rounding to tens, hundreds, thousands...) is a good pattern to know.
float datatype like in a lot of other languages, but
Number object is used for both integers and
floating point numbers. Internally, numbers are just 64 bit floating point numbers (source: ecma262-6.com),
floating point precision into consideration!