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?

2 Answers 2

5

You're looking for toFixed

var str = "126389471.74000001";
var formattedStr = parseFloat(str).toFixed(2); // 2 dp
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.