Wednesday, February 4, 2015

JavaScript, remove trailing insignificant zeros after toFixed function




In JavaScript, toFixed function is used to convert a number into a string, keeping only two decimals:
For example
var num = 6.76789;
var n = num.toFixed(2);
return 6.77
var num = 6;
var n = num.toFixed(2);
 return 6.00

But How to remove trailing insignificant zeros?
We can use Number function or parseFloat function such as
 Number(num.toFixed(4)); 
or
 parseFloat(num.toFixed(4));

1 comment:

  1. This will not work for small numbers (ex: 0.00000012) which JS tends to display in exponential form...

    ReplyDelete