round off currency using regular exp

Multi tool use


round off currency using regular exp
I have multiple currency inputs i.e $1,869.96. I need to round up my currency into $1,870 as a whole number without any decimal places.
The regular expression I used is
"$"+ a.toFixed(0).replace(/(d)(?=(ddd)+(?!d))/g, "$1,");
Can anybody help me in modifying the existing one to round up the value as a whole number without decimal places.Thank you.
I don't get why aren't you using
Math.round()
.– Dez
yesterday
Math.round()
Do you really have commas in your number? You'll need to remove them before you use any math operations.
– Barmar
yesterday
You need to convert the string to float and then round it with Math.round
– Nerdvoso
yesterday
1 Answer
1
Try this:
function formatVal(a){
var c = '';
if(a.toString().indexOf('$') !== -1){
a = Math.round(Number(a.toString().replace(/[^0-9.-]+/g,"")));
if (isNaN(a)){
c=a;
}else {
c ="$"+a.toFixed(0).replace(/B(?=(d{3})+(?!d))/g, '$&,');
if(c == '$0'){ c = "";}
}
}
return c;
}
console.log(formatVal('$1,869.96'));
console.log(formatVal('$1,869'));
console.log(formatVal('sssss'));
console.log(formatVal(42));
toFixed(2)
should be toFixed(0)
– Barmar
yesterday
toFixed(2)
toFixed(0)
Actually my mistake, I have updated
– Nerdvoso
yesterday
Changing from
toFixed(2)
to toFixed(0)
seems to break comma insertion. Something like return '$' + number.toFixed(0).replace(/d(?=(d{3})+$)/g, '$&,');
seems to work...– ggorlen
yesterday
toFixed(2)
toFixed(0)
return '$' + number.toFixed(0).replace(/d(?=(d{3})+$)/g, '$&,');
Nice, this equal
return '$' + number.toFixed(0).replace(/B(?=(d{3})+(?!d))/g, '$&,');
– Nerdvoso
yesterday
return '$' + number.toFixed(0).replace(/B(?=(d{3})+(?!d))/g, '$&,');
Hey Nerdvoso, can you please modify the same in my existing code and see my rounding function. It will be a great help, Here is how my code looks like function formatVal(a){ a=parseInt(a); //return value based on numeric /non-numeric if (isNaN(a)){ c=a; }else { c ="$"+a.toFixed(0).replace(/(d)(?=(ddd)+(?!d))/g, "$1,"); } return c; }
– JainP
19 hours ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What do you mean. I don't get any decimal places using your regex.
– chevybow
yesterday