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
user2598794
7472 gold badges11 silver badges24 bronze badges
2 Answers 2
You're looking for toFixed
var str = "126389471.74000001";
var formattedStr = parseFloat(str).toFixed(2); // 2 dp
answered Mar 13, 2014 at 11:55
Insyte
2,2382 gold badges20 silver badges28 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
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
BenM
53.3k26 gold badges116 silver badges172 bronze badges
Comments
lang-js