Home > Web Front-end > JS Tutorial > How to Round Numbers to One Decimal Place in JavaScript?

How to Round Numbers to One Decimal Place in JavaScript?

Patricia Arquette
Release: 2024-11-28 09:17:12
Original
627 people have browsed it

How to Round Numbers to One Decimal Place in JavaScript?

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
Copy after login

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"
Copy after login

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;
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template