简体   繁体   English

小数点后只需要两位数

[英]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.

相关问题 JavaScript中的小数点后仅允许两位数 - Allow only two digits after decimal in javascript 如何在 jquery 或 javascript 中获得精确的两位数 - how to get exact two digits after decimal point in jquery or javascript 如何在javascript中显示小数点后两位数 - how to show two digits after decimal in javascript 在DataTables中仅显示小数点后的3位数 - Display only 3 digits after decimal in DataTables 用于检查值的正则表达式必须仅允许小数点后两位数字? - Regular Expression to check a value must allow only two digits after decimal point? 如何舍入浮点数,使小数点后只有两个尾随数字? - How can I round a float such that there are only two trailing digits after the decimal point? 如何在 NumberFormat 中获取小数点后的数字? - How get digits after the decimal points in NumberFormat? Javascript regExp接受十进制前12位和十进制后两位 - Javascript regExp to accept 12 digits before decimal and two digits after decimal 如何使Vue js vuetify输入只允许小数点前3位和小数点后2位 - How to make Vue js vuetify input allow only 3 digits before decimal and 2 digits after decimal 在javascript中删除两个小数点后的数字而不是圆形数字? - Delete digits after two decimal point not round number in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM