Home > Back-end >  In jQuery what to use to round decimal number in finance app
In jQuery what to use to round decimal number in finance app

Time:02-02

I am getting frustrated. All examples I can find lack basic math.

My problem: I need to round these values to 2 decimal places:

1,235 = 1,23
1,236 = 1,24
1,234 = 1,23

I tried

var num = 1,235;
Math.round(num * 100) / 100;
num.toFixed(2);
Math.round(num  'e2') 'e-2');

all fail in one of the cases.

Solutions world wide suggest that 1,235 should be rounded up to 1,24, but in our country, government said that it needs to round down to 1,23 - and here lies the problem.

CodePudding user response:

Inner workings of .round()

The usual rounding we know rounds from 0.5 onwards to the next whole number.

What round does under the hood is almost what you wanted to implement. However the key is using .floor().

Imagine a number 6.5. We want it rounded to 7. If you didn't have round() as a function how would you do that by hand?
Well, like this:

Math.floor(6.5   0.5);

So naturally this results in 7.0. A value like 6.1 would remain a 6. Good that's how we want that to work. So adding the cutoff-point where we want to round up and flooring the value means we get the rounded number.

We can now also do that with decimal places like you discovered. See example below.

Implement your own rounding

In your case, you want to do that with a decimal place. You were correct in multiplying by 100. But then you must apply the rounding example from above and use 0.4 instead of 0.5.

So you can just implement your own rounding. The code below will round from x.006 onward to the next unit.

// rounded: 1,23   1,23   1,24
var arr = [ 1.234, 1.235, 1.236 ];
arr.forEach((num) => {
  var rounded = Math.floor((num * 100.0)   .4) / 100.0;
  console.log( 'Result=', rounded, 'toFixed(2)=', rounded.toFixed(2), 'Original=', num);
});

  • Related