I was playing around with these 3 function in javascript until I notice they all give the incorrect rounding value. Let say the following senario
var x = 1.49849;
Math.round(x) //return 1, but from what I learnt from school it should be 2, right?
x.toFixed() //return 1 too! same as rounding
x.toFixed(3) //return 1.498, shouldn't it be 1.499?
x.toFixed(4) //return 1.4985, at least this is working correctly....
I tried toPrecision() it is basically same with toFixed().
It looks like the rounding in javascript only consider one number right to it and ignored the rest of the decimal point.
Is there any javascript work around for this type of senario?
I know I can always do this in server side, but lets just focus on javascript.
I was playing around with these 3 function in javascript until I notice they all give the incorrect rounding value. Let say the following senario
var x = 1.49849;
Math.round(x) //return 1, but from what I learnt from school it should be 2, right?
x.toFixed() //return 1 too! same as rounding
x.toFixed(3) //return 1.498, shouldn't it be 1.499?
x.toFixed(4) //return 1.4985, at least this is working correctly....
I tried toPrecision() it is basically same with toFixed().
It looks like the rounding in javascript only consider one number right to it and ignored the rest of the decimal point.
Is there any javascript work around for this type of senario?
I know I can always do this in server side, but lets just focus on javascript.
Share Improve this question edited Sep 24, 2013 at 8:49 georg 215k56 gold badges322 silver badges400 bronze badges asked Sep 24, 2013 at 8:33 Jerry LamJerry Lam 4521 gold badge7 silver badges22 bronze badges 4- 5 please next time do your homework 1.49849 the nearest integer is 1 – Johannes Commented Sep 24, 2013 at 8:37
- 1 "but from what I learnt from school it should be 2, right?" Wrong! – nmaier Commented Sep 24, 2013 at 8:37
- 1 round, goes to the closest integer, so 49849 in one side and 50151 in the other, same for others – Jonathan de M. Commented Sep 24, 2013 at 8:38
- Your mistake is that rounding is not applied from right to left sequentially. Round to one place is not the same as to round to two places and then to one. – georg Commented Sep 24, 2013 at 9:00
1 Answer
Reset to default 10No, you are wrong.
1.49849 rounded to the nearest integer is 1, because the first digit after the decimal point is 4 which is smaller than 5.
1.49849 rounded to three digits after decimal point is 1.498 because the 4-th digit is 4.
It would be rounded up only if the first digit that you round was 5 or higher. In some financial rounding systems, exact halves are rounded to the nearest even number, so 2.5 rounds to 2, but 3.5 rounds to 4.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744891103a4599417.html
评论列表(0条)