jquery - how to round up if value is two decimal and format as 3 decimals in javascript? -
test cases:
var num1 = 10.66; var num2 = 10.7898
the function found on stackoverflow:
function formatusercurrencyvalue(fieldvalue){ var num = parsefloat(fieldvalue); var str = num.tofixed(10); str = str.substring(0, str.length-7); return str; };
i result this: if 10.66
10.670
, if 10.78998
10.789
. if value has 2 decimal places result should round first , format 3 decimals. if more 2 decimals (eg. 10.78998
) 10.789
, trimming out values after 3 decimals.
could please tell me how can achieve this? tried above function others found result not expected 10.66
scenario. getting 10.660
instead of 10.670
.
it looks similar question has been asked here: formatting number 2 decimals in javascript
i liked answer @miguel had. using function conversion.
function precise_round(num, decimals) { var t=math.pow(10, decimals); return (math.round((num * t) + (decimals>0?1:0)*(math.sign(num) * (10 / math.pow(100, decimals)))) / t).tofixed(decimals); }
then use function. precise_round(num,3)
Comments
Post a Comment