user2565589
user2565589

Reputation: 573

.toFixed not for .0*

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?

Upvotes: 54

Views: 32987

Answers (4)

akamaox
akamaox

Reputation: 1

How about this:

parseFloat((2199.004).toFixed(2)) // 2199

Upvotes: 0

Paul S.
Paul S.

Reputation: 66304

Assuming you want String outputs

function myFixed(x, d) {
    if (!d) return x.toFixed(d); // don't go wrong if no decimal
    return x.toFixed(d).replace(/\.?0+$/, '');
}
myFixed(1.0000, 2); // "1"
myFixed(1.1000, 2); // "1.1"
myFixed(1.1200, 2); // "1.12"
myFixed(1.1230, 2); // "1.12"

Upvotes: 23

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

The "correct" way to do it is as follows:

return Math.round(num*100)/100;

If you want to truncate it to two decimal places (ie. 1.238 goes to 1.23 instead of 1.24), use floor instead of round.

Upvotes: 12

Blazemonger
Blazemonger

Reputation: 92893

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

return parseFloat(val.toFixed(2));

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

Upvotes: 125

Related Questions