javascript - Comment arrondir à la plupart des 2 décimales, si nécessaire

Mots clés : javascriptroundingdecimal-pointjavascript

meilleur 5 Réponses javascript - Comment arrondir à la plupart des 2 décimales, si nécessaire

vote vote

97

Math.round(num * 100) / 100 
Math.round((num + Number.EPSILON) * 100) / 100 
vote vote

85

parseFloat("123.456").toFixed(2); 
var numb = 123.23454; numb = numb.toFixed(2); 
var numb = 1.5; numb = +numb.toFixed(2); // Note the plus sign that drops any "extra" zeroes at the end. // It changes the result (which is a string) into a number again (think "0 + foo"), // which means that it uses only as many digits as necessary. 
Math.round(1.005 * 100)/100 // Returns 1 instead of expected 1.01! 
parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56. parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56. // However, it will return correct result if you round 1.5551. parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.  1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356. // However, it will return correct result if you round 1.35551. 1.35551.toFixed(2); // Returns 1.36 as expected. 
function roundNumber(num, scale) {   if(!("" + num).includes("e")) {     return +(Math.round(num + "e+" + scale)  + "e-" + scale);   } else {     var arr = ("" + num).split("e");     var sig = ""     if(+arr[1] + scale > 0) {       sig = "+";     }     return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);   } } 
Math.round((num + Number.EPSILON) * 100) / 100 
vote vote

79

function roundToTwo(num) {         return +(Math.round(num + "e+2")  + "e-2"); } 
roundToTwo(1.005) 1.01 roundToTwo(10) 10 roundToTwo(1.7777777) 1.78 roundToTwo(9.1) 9.1 roundToTwo(1234.5678) 1234.57 
vote vote

63

Number.prototype.round = function(places) {   return +(Math.round(this + "e+" + places)  + "e-" + places); } 
var n = 1.7777;     n.round(2); // 1.78 
it.only('should round floats to 2 places', function() {    var cases = [     { n: 10,      e: 10,    p:2 },     { n: 1.7777,  e: 1.78,  p:2 },     { n: 1.005,   e: 1.01,  p:2 },     { n: 1.005,   e: 1,     p:0 },     { n: 1.77777, e: 1.8,   p:1 }   ]    cases.forEach(function(testCase) {     var r = testCase.n.round(testCase.p);     assert.equal(r, testCase.e, 'didn\'t get right number');   }); }) 
vote vote

56

Math.round( num * 100 + Number.EPSILON ) / 100 
Math.round( ( num + Number.EPSILON ) * 100 ) / 100 
const ESPILON_RATE = 1 + Number.EPSILON ; const ESPILON_ZERO = Number.MIN_VALUE ;  function epsilonEquals( a , b ) {   if ( Number.isNaN( a ) || Number.isNaN( b ) ) {     return false ;   }   if ( a === 0 || b === 0 ) {     return a <= b + EPSILON_ZERO && b <= a + EPSILON_ZERO ;   }   return a <= b * EPSILON_RATE && b <= a * EPSILON_RATE ; } 

Questions similaires