4

I have a floating point number in JavaScript, like 42.563134634634. I want to display it as a string "42.56", with exactly two decimal places. How do I do that?

5 Answers 5

6

Use toFixed method:

var num = 42.563134634634;
alert(num.toFixed(2));
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I've never even heard of that method before. Nice!
2

You could do

var num = 42.563134634634;
var res = num.toFixed(2);

Comments

0
function roundNumber(number, decimals) { // Arguments: number to round, number of decimal places
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    return newnumber;
}

1 Comment

If number needs to be converted, better to see that conversion does not error. If number type is assumed, then conversion seems pointless. parseInt(decmials) is redundant since the first step in the toFixed algorithm is to call toInteger(arg) (ECMA-262 15.7.4.5).
0

Have you read this ? http://forums.devarticles.com/javascript-development-22/javascript-to-round-to-2-decimal-places-36190.html

Comments

0
function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.