Javascript: Display float with 2 decimal places (3 examples)
There are several ways to format a float with 2 (or any number you want) decimal places in Javascript.
Example 1: Using toFixed()
The code:
const x = 1 / 3;
const y = 82.232434023923;
const z = 4 / 7;
console.log(x.toFixed(2));
console.log(y.toFixed(2));
console.log(z.toFixed(3));
Output:
0.33
82.23
0.571 // 3 decimal places
Example 2: Using toLocaleString()
The code:
var a = 1.43233444;
var b = 8 / 11;
var c = 432.233232499;
console.log(
a.toLocaleString("en-US", {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
})
);
console.log(
b.toLocaleString("en-US", {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
})
);
console.log(
c.toLocaleString("en-US", {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
})
);
Output:
1.43
0.73
432.23
Example 3: Using toPrecision()
The code:
var d = 11 / 3;
var e = 222.33029293;
var f = 0.9343434343434;
console.log(d.toPrecision(3))
console.log(e.toPrecision(5))
console.log(f.toPrecision(2))
Notice that the number you pass to the toPrecision method is the number of significant digits in your results.
Output:
3.67
222.33
0.93
You can find more information about the toPrecision method on the Mozilla website.
What’s Next?
We’ve gone through a few examples of formating float numbers in Javascript. If you’d like to explore more interesting stuff about this programming language, take a look at the following articles:
- Javascript: 5 ways to create a new array from an old array
- Simple Promise chain example in modern Javascript (ES6+)
- Javascript: Get current date time as 20xx/00/00 00:00:00 format
- Node.js: Ways to Create a Directory If It Doesn’t Exist
You can also check out our Javascript topic page for more tutorials and examples. Happy coding!
Subscribe
0 Comments