2

I have this problem with rounding up or rounding off with javascript. Well it gets the job done but there are some scenarios that it fails to do the job properly.

For example.

The price is 0.30 with a 15% discount should have 0.255 or 0.26 as result. (this is somehow okay)

The price is 79.99 with a 50% discount should have 40 as result. (actual result is 39.995)

Tried using this as reference Using toFixed(2) and math round to get correct rounding

also did this process Math.round(value*Math.pow(10,dec))/Math.pow(10,dec);

Any ideas?

Thanks

This is my initial test. Though this is just an initial test what I did is checked if the last two digits is greater than 5 then apply Math.ceil that would to the 0.255 to be 0.26 but when using 39.99 the result would still be 39.99 though 39.99 should use Math.round so that the result would be 40.

What I would like to accomplish is to be able to round up or round down any number if it needs rounding up or if it needs rounding up.

UPDATE

I was able to solve my own problem. (Atleast to my specific environment)

http://jsfiddle.net/xMj3M/4/

Community
  • 1
  • 1
n0minal
  • 3,195
  • 9
  • 46
  • 71
  • 3
    I don't understand your question, what degree of accuracy would you like to accomplish? You'd like precision of two decimal places in the first place and of none or 1 decimal place in the second – Benjamin Gruenbaum Mar 07 '13 at 23:54
  • @Benjamin Gruenbaum: in both cases it's rounding up to 2 decimals places – zerkms Mar 07 '13 at 23:59
  • This should answer your question for two decimal precision: http://stackoverflow.com/questions/5191088/how-to-round-up-a-number-in-javascript – Mehdi Karamosly Mar 08 '13 at 00:05
  • @MehdiKaramosly that answer forces a round up e.g. .ceil() I'm not sure that was the OP's desire. – scunliffe Mar 08 '13 at 00:14
  • in commerce better round up than round down... – Mehdi Karamosly Mar 08 '13 at 00:25
  • please clarify what you are getting as a result of your initial code posted in the question that **wasn't** what you wanted? e.g. what is the part you want us to help resolve? – scunliffe Mar 08 '13 at 00:35

2 Answers2

2

This is because of how floats are handled. I would suggest having your original numbers in integers only, so you would start with 7999. If you use this method, you will get the correct result.

In general, especially when dealing with money, it is always a good idea to work in pennies first, and then output it in the format of the currency.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

You could try:

var someNumber = 36.7327;
var someNumberRoundedTo2Decimals = (Math.round((someNumber * 100)) / 100);
// = 36.73

basically this moves the decimal to the right 2 digits..

3673.27

then rounds it off to an int

3673

then moves the decimal back to the left 2 places

36.73
scunliffe
  • 62,582
  • 25
  • 126
  • 161