How to format thousands with dot and decimal with comma?
Input: 3197769.7000000007
Expected: 3.197.769,7000000007
Tried the following regex but doesn't feel clean enough. I feel like answer should be similar to https://stackoverflow.com/a/2901298/11328122 but I don't have enough regex knowledge for it.
const value = 3197769.7000000007
console.log(value.toString().replace(/\B(?<!\.\d*)(?=(\d{3}) (?!\d))/g, "#").replace('.', ',').replace(/#/g, '.'));
CodePudding user response:
You can use the Intl.NumberFormat method to format numbers:
const value = 3197769.7000000007;
const formatter = new Intl.NumberFormat('de-DE', {
style: 'decimal',
useGrouping: true,
maximumFractionDigits: 20
});
// Output: 3.197.769,7000000007
console.log(formatter.format(value));
CodePudding user response:
I agree that regex is not the best suited tool since the Internationalization Web API offers safer and more convenient solutions. Anyhow what I see from the OP's used regex and also from the linked thread, I have to say that there are much cleaner and more straightforward regex and replace
based solutions like e.g. this one ...
console.log(
'3197769.7000000007 =>',
String(3197769.7000000007)
// - replace the standard decimal separator by a comma.
.replace('.', ',')
// - see ... [https://regex101.com/r/3pvKHl/1]
// - replace every digit which is followed
// by a sequence of 3-digit groups/blocks
// until the comma by the very digit itself
// and the thousands block separating dot.
.replace(/\d(?=(?:(?:\d{3}) ),)/g, match => `${ match }.`)
);
console.log(
'6291563197769.587 =>',
String(6291563197769.587)
.replace('.', ',')
.replace(/\d(?=(?:(?:\d{3}) ),)/g, match => `${ match }.`)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
... where one would
e.g. cast the number into a string value via the
String
function,replace
the sole occurrence of the decimal delimiter (dot) by a comma,replace
every digit which is followed by a sequence of 3-digit groups/blocks until the comma by the very digit itself and the thousands block separating dot ...... with the help of following regex ...
/\d(?=(?:(?:\d{3}) ),)/g
where the regex reads as follows .../ \d (?= (?:(?:\d{3}) ), ) /g
...g
lobally match a single digit/\d
followed by a lookahead/(?= ... )
where the pattern of the lookahead(?:(?:\d{3}) ) ,
... enforces a comma which is headed by at least a single block of exactly 3 digits/\d{3}
which also is allowed to become a sequence of blocks of always 3 digits each/(?:\d{3})
.Note ... the pattern
(?: ... )
is used for grouping where the matching expression is meant to not be captured.