Dowemo


Question:

Am I missing something here?

var someNumber = 123.456;


someNumber = someNumber.toFixed(2);


alert(typeof(someNumber));


//alerts string


Why does .toFixed() return a string?

I want to round the number to 2 decimal digits.


Best Answer:


Number.prototype.toFixed is a function designed to format a number before printing it out. It's from the family of toString, toExponential and toPrecision.

To round a number, you would do this:

someNumber = 42.008;


someNumber = Math.round( someNumber * 1e2 ) / 1e2;


someNumber === 42.01;



// if you need 3 digits, replace 1e2 with 1e3 etc.


.

Or if you want a native-like function, here you are:

Number.prototype.toFixedNumber = function(x, base){


  var pow = Math.pow(base||10,x);


  return +( Math.round(this*pow) / pow );


}


someNumber = 42.008;


someNumber = someNumber.toFixedNumber(2);


someNumber === 42.01;



//or even hexadecimal



someNumber = 0xAF309/256  //which is af3.09


someNumber = someNumber.toFixedNumber(1, 16);


someNumber.toString(16) === "af3.1";


.

Tho I don't like jsperf that much, here's a link with comparsion of the method using conversion (in other answers) and this one:
https://jsperf.com/rounding-a-number-2




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs