本文主要是介绍js中金额进行千分以及toFixed()保留两位小数丢失精度的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、金额进行千分
function commafy(num) {
if ((num + "").trim() == "") {
return "";
}
if (isNaN(num)) {
return "";
}
num = num + "";
if (/^.*\..*$/.test(num)) {
const pointIndex = num.lastIndexOf(".");
const intPart = num.substring(0, pointIndex);
const pointPart = num.substring(pointIndex + 1, num.length);
intPart = intPart + "";
const re = /(-?\d+)(\d{3})/
while (re.test(intPart)) {
intPart = intPart.replace(re, "$1,$2")
}
num = intPart + "." + pointPart;
} else {
num = num + "";
const re = /(-?\d+)(\d{3})/
while (re.test(num)) {
num = num.replace(re, "$1,$2")
}
}
return num;
}
2、toFixed()保留两位小数丢失精度解决办法
function toFixedTwo(num) {
return (num*100).toFixed(0)/100
}
这篇关于js中金额进行千分以及toFixed()保留两位小数丢失精度的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!