使用 Math.round() 数字超过10000显示1点几的w 没超过返回原数 有小数保留两位,没有小数不保留小数点
时间: 2024-03-08 16:47:32 浏览: 18
你可以使用以下代码实现:
```JavaScript
function formatNumber(num) {
if (num >= 10000) {
return (Math.round(num / 100) / 100).toFixed(2) + 'w';
} else if (num >= 1) {
return num.toFixed(0);
} else if (num > 0) {
return num.toFixed(2);
} else {
return '0';
}
}
```
该函数接收一个数字作为参数,根据数字的大小和小数部分,返回相应的格式化字符串。具体来说:
1. 如果数字大于等于 10000,先将数字除以 10000,然后使用 Math.round() 函数将结果四舍五入到小数点后两位,并在末尾添加 'w',返回格式化后的字符串。
2. 如果数字大于等于 1 且小于 10000,则直接使用 toFixed() 函数保留小数点后两位,并返回格式化后的字符串。
3. 如果数字大于 0 且小于 1,则同样使用 toFixed() 函数保留小数点后两位,并返回格式化后的字符串。
4. 如果数字等于 0,则返回字符串 '0'。
示例:
```JavaScript
console.log(formatNumber(1234)); // 输出 '1234'
console.log(formatNumber(12345)); // 输出 '1.23w'
console.log(formatNumber(123.45)); // 输出 '123.45'
console.log(formatNumber(0.123)); // 输出 '0.12'
console.log(formatNumber(0)); // 输出 '0'
```
需要注意的是,该函数仅适用于数字类型的参数,如果传入的参数类型不是数字,则需要进行类型检查和转换。