0

I am trying to do simple number rounding in javascript to round off values to 2 decimal places.(Excuse for poor english..)

After very little little research I found a solution which is as follows-

var num=1.234;
var result=Math.round(num*100)/100;

It's working fine in most of the cases except for one! If num conatins 1.345, mathematically after rounding off the result should be 1.34(When an even decimal (or any even number) is followed by a 5, you round down. When an odd decimal is followed by a 5, you round up.
For example: 75.45 = 75.4, but 75.55=75.6) But I am getting 1.35. So how can I get the desired result? Like when i pass 1.345, I get 1.34 and when I pass 1.335, I get 1.34 Because it's an API method I have almost idea as to what should I do. Can anyone help me out here.. Thanks in advance!!!

ValarDohaeris
  • 639
  • 1
  • 6
  • 21
  • rounding 1.345 to two decimal places will give 1.35. Are you looking for any custom rounding? – Nitheesh Jan 31 '17 at 06:15
  • 1
    no, rounding off 1.345 should always be 1.35 to two decimal places ... not sure where your rules of rounding come from, but they aren't the rules of floating point rounding ... – Jaromanda X Jan 31 '17 at 06:15
  • 1
    @JaromandaX: "When an even decimal (or any even number) is followed by a 5, you round down. When an odd decimal is followed by a 5, you round up" is ["round half to even"](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even), or Banker's rounding. Typically, programming languages support "round half up". – Amadan Jan 31 '17 at 06:18
  • That's some specialised rules there – Jaromanda X Jan 31 '17 at 06:22
  • @JaromandaX: It's likely the best rule to avoid bias. If you consistently round half up, a sum of many rounded items will tend to be slightly greater than a rounded sum of items, with the divergence growing proportionally to the number of items; one could theoretically get into Salami Slicing territory. With round half to even (or odd), the gains counterbalance the losses by the law of large numbers, given random data. However, it is a pain in the behind if you want a predictable rounding behaviour you need in most applications. So, yeah, "specialised" is a pretty apt term, I suppose. – Amadan Jan 31 '17 at 06:52
  • @JaromandaX Gaussian/banker's rounding is widely used in certain domains. The [Wikipedia page on rounding](https://en.wikipedia.org/wiki/Rounding) outlines more than a dozen different approaches to rounding, of which this is one of them. – JLRishe Jan 31 '17 at 07:17

0 Answers0