Reputation: 643
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?
Upvotes: 2
Views: 555
Reputation: 125
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)
Upvotes: 0
Reputation: 2994
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);
Upvotes: 2
Reputation: 20039
Try toLocaleString()
let result = Number("21708.333333333336").toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
console.log(result)
Upvotes: 5