18 November 2008

Floating Point Precision in JavaScript

There is an unusual-named function in JavaScript for floating point precision - toFixed. I am really surprised at this naming.

Function singnature:
string toFixed (noOfdigit)

Example:

var n = 3.7345;
var n1 = n.toFixed(2); // n1 = 3.73
var n2 = n.toFixed(3); // n2 = 3.735


Note: toFixed function return a string, NOT a number. So, to get a number, you have to use parseFloat function. For example,

var
n1 = parseFloat( n.toFixed(2) ) ;

0 Comments:

 

© 2007 t!ps n tr!cks: Floating Point Precision in JavaScript



Template unik dari rohman


---[[ Skip to top ]]---