JavaScript toFixed method formats a number with a specific number of digits to the right of the decimal. This means you can set numbers to a fixed decimal length.
Note:
- It converts a number into a string and rounding to a specified number of decimals.
- Zero added a decimal point if the given number of decimals is higher than the actual number.
Syntax
number.toFixed(x)
Example of JavaScript toFixed method
Example of rounding the number to keep only thee decimals in JavaScript.
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var num = 98.33668;
var n = num.toFixed(3);
alert(n);
</script>
</body>
</html>
Output:
JavaScript toFixed without rounding
We have a number var x = 2.305185185185195;
x = x.toFixed(5);
x = 2.30519
but require this without rounding i.e. 2.30518
Basically, this solution moves the point to the left with a factor of 10^d and gets an integer of that and divided the value with the former factor to get the right digits.
function getFlooredFixed(v, d) {
return (Math.floor(v * Math.pow(10, d)) / Math.pow(10, d)).toFixed(d);
}
var x = 2.305185185185195;
document.write(getFlooredFixed(x, 5));
Do comment if you have any questions and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version