写一个js方法,给数字整数部分加千分位
时间: 2024-02-01 19:04:12 浏览: 117
以下是一个实现给数字整数部分加千分位的 JavaScript 方法:
```js
function addThousandSeparator(num) {
// 将数字转成字符串,方便处理
let strNum = String(num);
// 分割整数部分和小数部分
let [intPart, decimalPart] = strNum.split('.');
// 如果没有小数部分,将整数部分每三位加一个逗号
if (!decimalPart) {
let str = '';
for (let i = intPart.length - 1, j = 0; i >= 0; i--, j++) {
if (j > 0 && j % 3 === 0) {
str = ',' + str;
}
str = intPart[i] + str;
}
return str;
}
// 如果有小数部分,将整数部分每三位加一个逗号,再拼接上小数部分
let str = '';
for (let i = intPart.length - 1, j = 0; i >= 0; i--, j++) {
if (j > 0 && j % 3 === 0) {
str = ',' + str;
}
str = intPart[i] + str;
}
return str + '.' + decimalPart;
}
```
用法示例:
```js
console.log(addThousandSeparator(1234567)); // "1,234,567"
console.log(addThousandSeparator(1234567.89)); // "1,234,567.89"
console.log(addThousandSeparator(9876543210)); // "9,876,543,210"
console.log(addThousandSeparator(0)); // "0"
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)