[英]Need to get only two digits after decimal
I have string with below format 我有以下格式的字符串
const number = "21708.333333333336"
Then I pass it to the function to get the number in this format 然后我将其传递给函数以获取此格式的数字
"21,708.333333333336"
Function I am using for to do this (I have tried this) 我用于执行此功能(我已经尝试过)
let numberFormat = (x) => {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
But I need only last 2 digits 但是我只需要最后两位数字
"21,708.33"
What should be the regex for this? 正则表达式应该是什么?
Try toLocaleString()
尝试
toLocaleString()
let result = Number("21708.333333333336").toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) console.log(result)
Before passing it to function which convert it to string use 在将其传递给将其转换为字符串的函数之前,请先使用
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
let number = "21708234234324.333333333336"
number = Number(number).toFixed(2);
numberWithCommas(number);
Try this code with basic funtionality 使用基本功能尝试此代码
const number = "21708.333333333336"
function splitValue(value, index) {
return parseInt(value.substring(0, index)) + "," + calc(value.substring(index));
}
function calc(theform) {
var with2Decimals = theform.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
return parseInt(with2Decimals);
}
var val = splitValue(number, 2);
console.log(val)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.