0

I have numbers in table and need to format them with JavaScript (2 symbols after dot). This code works but I guess there are more efficient and elegant ways:

var str = "126389471.74000001";
var dotIndex = str.indexOf(".");
var formattedStr = str.substring(0, dotIndex+3);

Could anybody suggest better solution?

asked Mar 13, 2014 at 11:53

2 Answers 2

5

You're looking for toFixed

var str = "126389471.74000001";
var formattedStr = parseFloat(str).toFixed(2); // 2 dp
answered Mar 13, 2014 at 11:55
Sign up to request clarification or add additional context in comments.

Comments

1

Why do you treat them as strings in the first place? It would be much better to use JavaScript to automatically handle this with toFixed():

var num = 126389471.74000001,
 formatted = num.toFixed(2);

jsFiddle Demo

If you absolutely have to treate it as a string, use parseFloat() and the same method:

var formatted = parseFloat(num).toFixed(2);
answered Mar 13, 2014 at 11:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.