math - Rounding away from zero in Javascript -
we building table in javascript handsontable representing currency amounts. give user possibility of render amounts 2 decimal places or no decimal places (it's requirement client). , find things this:
column column b column c = + b ------------------------------------------- -273.50 273.50 0 2 decimals -273 274 0 no decimals
investigating little came find basic rounding function in javascript, math.round()
, works this:
if fractional portion 0.5, argument rounded next integer in direction of +∞. note differs many languages'
round()
functions, round case next integer away zero, instead (giving different result in case of negative numbers fractional part of 0.5).
as dealing currency amounts, not care happens after second decimal place, chose add -0.0000001 negative value in table. thus, when rendering values 2 or no decimals, proper results, math.round(-273.5000001)
= -274, , math.round(-273.4900001)
still -273.
nonetheless, find finer solution problem. best, elegant way achieve (that not require modifying original numeric value)? note not directly call math.round(x)
, tell handsontable format value given number of decimal places.
as @dandavis noted in comments, best way handle use .tofixed(2)
instead of math.round()
.
math.round()
, noted, rounds half up.
.tofixed()
round half away zero. designate 2
in there indicate amount of decimals use when doing rounding.
Comments
Post a Comment