.toFixed not for .0*

user2565589 picture user2565589 · Jul 9, 2013 · Viewed 18.6k times · Source

I have a few values:

var one = 1.0000
var two = 1.1000
var three = 1.1200
var four = 1.1230

and function:

function tofixed(val)
{
   return val.toFixed(2);
}

this return:

1.00
1.10
1.12
1.12 

LIVE

I want maximum size after dot - 2, but only if numbers after for != 0. So i would like receive:

1
1.1
1.12
1.12 

How can i make it?

Answer

Blazemonger picture Blazemonger · Jul 9, 2013

.toFixed(x) returns a string. Just parse it as a float again:

return parseFloat(val.toFixed(2));

http://jsfiddle.net/mblase75/y5nEu/1/