19

I have a string n which is a number. The following adds the commas where needed, but I also want to change the number of decimals. It should also round where appropriate.

var parts = n.split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");

This turns a number like 1234.567 in to 1,234.567. But I need my number to look like: 1,234.57

I tried taking parts[1] and converting to a Number, then rounding, then concatenating it back; but that is error prone.

How can I get this result by altering my regex? Thanks.

9 Answers 9

47

Edit: Sept 18, 2019

Since new APIs are available, thought it would be helpful to point out that you can do this much more simply using toLocaleString options:

const numbers = [1, 1000, 2345.67, 21589.334719999995];
const options = { 
  minimumFractionDigits: 2,
  maximumFractionDigits: 2 
};
numbers.forEach(num => {
  const formatted = Number(num).toLocaleString('en', options);
  console.log(formatted);
});


original answer

To add the commas, you could use:

n = parseFloat(n).toFixed(2)
var withCommas = Number(n).toLocaleString('en');

Here is a fiddle

Sign up to request clarification or add additional context in comments.

6 Comments

I collapsed the whole thing to Number(parseFloat(n).toFixed(2)).toLocaleString('en');
@RobM. But I tested with 123949.1, it does not return me with 2 decimal point. Is there any workaround for it?
I tested with n=1. Returns 1, expected 1.00 (does not work :'( )
@daCoda Right, you would need to use the maximumFractionDigits option for that
This: Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }). Thanks!
|
8
var val = Math.round(Number(n) *100) / 100;
var parts = val.toString().split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");

Comments

3

You could just use toFixed

var parts = (+n).toFixed(2).split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (+parts[1] ? "." + parts[1] : "");

FIDDLE

That would also make 1234.0000 to 1234.00, but you can avoid that by converting to a number in the ternary, as zero is falsy

4 Comments

n is a string, so I cant use toFixed(). n needs to stay a string for other reasons.
@brno792 - I'm sorry to break it to you, but you can't round a string, no matter how hard you try.
You could of course just slice of the end of the string with parts[1].slice(0,2), but that would give you 1234.56 as it doesn't round.
Yes, I am well aware of that.. your solution is no help though.
1

i think this is useful

var n=1234.567
var parts = n.toFixed(2).split(".");
var num = parts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + 
    (parts[1] ? "." + parts[1] : "");
console.log(num);

if you want result 1,234.567 then change toFixed(2) to toFixed(3)

Comments

1
var valueString="1500"; //can be 1500.0 or 1500.00 
var amount=parseFloat(valueString).toFixed(2);
var formattedString= amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(formattedString); //outputs 1,500.00

1 Comment

Thanks for your answer. Typically, it's helpful to write a few remarks outside of the code block that explains how the code works for future readers.
0

When it comes to formatting currency in JavaScript, toLocaleString is great. You don't need to combine it with toFixed and it will not work in some cases (whole numbers, numbers with single-digit fractions). Here's an example function:

const formatCurrency = (num, locale = 'en-US', currency = 'USD', minimumFractionDigits = 2) => {
    if (isNaN(num)) {
        return num;
    }
  return num.toLocaleString(locale, {style: 'currency', currency, minimumFractionDigits});
};

No super-customized string format patterns and no chained methods that work in specific scenarios.

Here is an example fiddle

Comments

0

To avoid that by converting to a number in the ternary, as zero is falsy

n = parseFloat(n).toFixed(2)
var withCommas = Number(n).toLocaleString('en');
withCommas = (withCommas.indexOf(".")== -1) ? `${withCommas}.00` : withCommas;

Comments

0

Adding onto @Rob M's answer (for a minimum AND maximum of 2dp):

function getMe2DecimalPointsWithCommas(amount) {
    return Number(amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

Comments

0

I think this is the easy way to format the Number with different Locale

const NumberFormatter = (value, decimal) => {
  return parseFloat(parseFloat(value).toFixed(decimal)).toLocaleString(
    "en-IN",
    {
      useGrouping: true,
    }
  );};

Instead of "en-IN" you can specify Language. like ‘ja-JP’,’en-US’ and ‘de-DE’, etc. It will group the number with the symbol based on the locale.

Ref: Format Numbers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.