4
Math.round(num * 100) / 100

Case 1:

15.625 * 19 = 296.875

When we apply the code above, the final result is 296.88 which is correct.

var test = 15.625 * 19;
test = Math.round(test * 100) / 100;
console.log( test ); // Return 296.88 (Correct)

Case 2:

15.225 * 19 = 289.275

When we apply the code above, the final result is 289.27 which is not correct.

var test = 15.225 * 19;
test = Math.round(test * 100) / 100;
console.log( test ); // Return 289.27 (Not correct)

Hence, I tried to breakdown and found out that:

289.275 * 100 = 28927.499999999996
Math.round(28927.499999999996) = 28927
Then, 28927/100 = 289.27

The suppose to be 0.5 turned into 0.499999999996 after multiply by 100

(^ This is the part I'm stuck and not sure how to proceed)

For temporary usage, I did something like this as below:

var compiledPrice = 289.275;
console.log( 'compiledPrice1 : ' + compiledPrice );
// 289.275

compiledPrice = compiledPrice * 10;
console.log( 'compiledPrice2 : ' + compiledPrice );
// 2892.75

compiledPrice = compiledPrice.toFixed(1);
console.log( 'compiledPrice3 : ' + compiledPrice );
// 2892.8

compiledPrice = compiledPrice / 10;
console.log( 'compiledPrice4 : ' + compiledPrice );
// 289.28000000000003

compiledPrice = compiledPrice.toFixed(2);
console.log( 'compiledPrice5 : ' + compiledPrice );
// 289.28

I'm not sure is this the proper way to solve this issue, I hope somebody would able to shed some light to me please.

creolyte
  • 41
  • 4
  • 1
    how about `+Intl.NumberFormat('en', {useGrouping: false, maximumFractionDigits: 2}).format(289.275)` – ProDec Dec 04 '21 at 05:31
  • 1
    Does this answer your question? [How to round to at most 2 decimal places, if necessary?](https://stackoverflow.com/questions/11832914/how-to-round-to-at-most-2-decimal-places-if-necessary) – Nguyễn Ngọc Hùng Long Dec 04 '21 at 06:15
  • @NguyễnNgọcHùngLong Before I posted this question, I was using that solution for quite a while until I have this rounding issue with "289.275" var test = Math.round((289.275 + Number.EPSILON) * 100) / 100 The above method will return "289.275", by right should be "289.28" – creolyte Dec 08 '21 at 05:58
  • Hi @ProGu, I tested your method and it works! Tested on 289.270, 289.271, 289.272... until 289.279 all rounded to 2 decimal places like wanted, and shorter solution compared to my temporary hack. If I hit any issues I'll update here for everyone's benefit, but so far so good as for now :) ``` var test = Intl.NumberFormat('en', {useGrouping: false, maximumFractionDigits: 2}).format(289.275) console.log( test ); // Return 289.28 ``` – creolyte Dec 08 '21 at 06:02

0 Answers0