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?

user2598794
  • 697
  • 2
  • 10
  • 23

2 Answers2

5

You're looking for toFixed

var str = "126389471.74000001";
var formattedStr = parseFloat(str).toFixed(2); // 2 dp
Ian Brindley
  • 2,197
  • 1
  • 19
  • 28
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);
BenM
  • 52,573
  • 26
  • 113
  • 168