0

I'm tried many things but I still have a problem, example: 4.3725 * 350 = 1530.38 but my result is 1530.37 ;/

I tried this:

Number.prototype.round = function(places) {
  return +(Math.round(this + "e+" + places)  + "e-" + places);
}

and toFixed.

Teemu
  • 22,918
  • 7
  • 53
  • 106
Alterwar
  • 3
  • 2

1 Answers1

0

You could use toPrecision(). This returns a string which you can just convert back to a Number and round.
The problem was toFixed() rounds numbers like that: 3.65.toFixed(1) => 3.6
Math.round(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
Here an example:

   function roundTo(number, digits)  {
        var roundHelp = Math.pow(10, digits); // needed to round to correct number of decimals
        number = Number(number.toPrecision(15));
        return Math.round(number * roundHelp)/roundHelp;
        // if you want the exact number of digits use this return statement:
        // return (Math.round(number * roundHelp)/roundHelp).toFixed(digits);
   }
   var x = roundTo(4.3725 * 350, 2);  // x = 1530.38
   var y = roundTo(4.2970 * 535, 2);  // y = 2298.9
darron614
  • 893
  • 7
  • 15