📜  javascript round float - Javascript (1)

📅  最后修改于: 2023-12-03 14:42:26.929000             🧑  作者: Mango

JavaScript Rounding Float

Working with floating point numbers can sometimes lead to unexpected results due to the limitations of computer representation of numbers. Therefore, sometimes it becomes necessary to round the floating point numbers to a desired number of decimal places. In JavaScript, there are several methods to round a floating point number.

Math.round()

Math.round() is a built-in JavaScript math function that rounds a number to the nearest integer.

let num = 3.7;
let rounded = Math.round(num);
console.log(rounded); // Output: 4
toFixed()

toFixed() is a built-in JavaScript function that rounds a number to a specified number of decimal places and returns the result as a string.

let num = 3.14159265359;
let fixed = num.toFixed(2);
console.log(fixed); // Output: '3.14'
parseFloat() and toFixed()

We can also use parseFloat() to convert a string to a number and then use toFixed() to round it to a specified number of decimal places.

let numStr = '3.14159265359';
let num = parseFloat(numStr);
let fixed = num.toFixed(2);
console.log(fixed); // Output: '3.14'
Summary

In this article, we have discussed different methods of rounding a floating point number in JavaScript. We can use Math.round() to round a number to the nearest integer, toFixed() to round a number to a specified number of decimal places and return it as a string, or use parseFloat() and toFixed() in combination to convert a string to a number and then round it to a specified number of decimal places.