在 JavaScript 中,获取两位小数的方法包括:使用 toFixed() 方法返回一个指定小数位数的字符串。使用 Number.prototype.toLocaleString() 方法指定 {minimumFractionDigits: 2} 选项格式化为两位小数。使用自定义函数 toFixed2(num) 截取小数点后两位。

如何用 JS 获取两位小数
在 JavaScript 中,有几种方法可以获取两位小数:
1. 使用 toFixed() 方法
toFixed() 方法返回一个指定小数位数的字符串。要获取两位小数,可以使用以下语法:
const numString = number.toFixed(2);
例如:
const num = 3.14159; const numString = num.toFixed(2); // "3.14"
2. 使用 Number.prototype.toLocaleString() 方法
toLocaleString() 方法返回一个语言和区域特定的字符串表示形式的数字。可以通过指定 {minimumFractionDigits: 2} 选项来格式化为两位小数:
const numString = number.toLocaleString("en-US", {minimumFractionDigits: 2});例如:
const num = 3.14159;
const numString = num.toLocaleString("en-US", {minimumFractionDigits: 2}); // "3.14"3. 使用自定义函数
如果需要更多的控制,可以使用自定义函数来获取两位小数:
function toFixed2(num) {
return num.toString().slice(0, num.toString().indexOf('.') + 3);
}例如:
const num = 3.14159; const numString = toFixed2(num); // "3.14"










