javascript - Reliable JS rounding numbers with toFixed(2) of a 3 decimal number -
i trying round 1.275.tofixed(2)
, expecting return of 1.28, rather 1.27.
using various calculators , simple method of rounding nearest hundredth, if last digit greater or equal to five, should round up.
if doesn't work tofixed(2), how it?
people asking whether console.log(1.275.tofixed(2)) prints off 1.28, here's quick screenshot macos chrome version 55.0.2883.95 (64-bit)
the tofixed()
method unreliable in rounding (see Álvaro gonzález' answer why case).
in both current chrome , firefox, calling tofixed()
yields following inconsistent results:
35.655.tofixed(2) // yields "36.66" (correct) 35.855.tofixed(2) // yields "35.85" (wrong, should "35.86")
mdn describes reliable rounding implementation:
// closure (function() { /** * decimal adjustment of number. * * @param {string} type type of adjustment. * @param {number} value number. * @param {integer} exp exponent (the 10 logarithm of adjustment base). * @returns {number} adjusted value. */ function decimaladjust(type, value, exp) { // if exp undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return math[type](value); } value = +value; exp = +exp; // if value not number or exp not integer... if (isnan(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return nan; } // shift value = value.tostring().split('e'); value = math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); // shift value = value.tostring().split('e'); return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); } // decimal round if (!math.round10) { math.round10 = function(value, exp) { return decimaladjust('round', value, exp); }; } // decimal floor if (!math.floor10) { math.floor10 = function(value, exp) { return decimaladjust('floor', value, exp); }; } // decimal ceil if (!math.ceil10) { math.ceil10 = function(value, exp) { return decimaladjust('ceil', value, exp); }; } })(); // round math.round10(55.55, -1); // 55.6 math.round10(55.549, -1); // 55.5 math.round10(55, 1); // 60 math.round10(54.9, 1); // 50 math.round10(-55.55, -1); // -55.5 math.round10(-55.551, -1); // -55.6 math.round10(-55, 1); // -50 math.round10(-55.1, 1); // -60 math.round10(1.005, -2); // 1.01 -- compare math.round(1.005*100)/100 above // floor math.floor10(55.59, -1); // 55.5 math.floor10(59, 1); // 50 math.floor10(-55.51, -1); // -55.6 math.floor10(-51, 1); // -60 // ceil math.ceil10(55.51, -1); // 55.6 math.ceil10(51, 1); // 60 math.ceil10(-55.59, -1); // -55.5 math.ceil10(-59, 1); // -50
Comments
Post a Comment