How to Round a Number to One Decimal Place in JavaScript
In JavaScript, you can round a number to one character after the decimal point using the following approach:
var num = 12.3456789; var rounded = Math.round(num * 10) / 10; console.log(rounded); // Output: 12.3
This works by multiplying the number by 10, rounding the result, and then dividing by 10 again. This ensures that only one decimal place is retained.
To round a number to one decimal place, even when that would be a 0, you can use .toFixed() as follows:
var rounded = num.toFixed(1); console.log(rounded); // Output: "12.3"
Note that .toFixed() returns a string, so you may need to convert it back to a number if necessary.
For added flexibility, you can create a custom round() function that takes a precision argument:
function round(value, precision) { var multiplier = Math.pow(10, precision || 0); return Math.round(value * multiplier) / multiplier; }
This function can be used as follows:
round(12345.6789, 2); // Output: 12345.68 round(12345.6789, 1); // Output: 12345.7 round(12345.6789); // Output: 12346 round(-123.45, 1); // Output: -123.4
The precision argument defaults to 0, which rounds the number to the nearest whole number.
The above is the detailed content of How to Round Numbers to One Decimal Place in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!