简体   繁体   中英

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()

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM