how can i convert "570.581,88" into an integer and sort accordingly?
2 Answers
var s = "570.581,88";
// Format as American input
s = s.replace(/\./g,'').replace(',','.');
// Integer
var i = parseInt(s,10);
// Floats
var f1 = parseFloat(s);
var f2 = s*1;
var f3 = +s;
1 Comment
Jason Thompson
Is there a locale neutral way of doing this? If my one person's locale is European and the other is American, will parseInt work differently?
A better way is using Intl.Numberformat to find out the decimal and group separator like so:
type Separators = { decimal: string; group: string };
const localeSeparators = (locale: string): Separators => {
const parts = new Intl.NumberFormat(locale).formatToParts(1000.5);
return {
decimal: parts.find((part) => part.type === 'decimal')?.value ?? '.',
group: parts.find((part) => part.type === 'group')?.value ?? ','
};
};
// logs `{decimal: ',', group: '.'}`
console.log(localeSeparators('de'));
// logs `{decimal: '.', group: ','}`
console.log(localeSeparators('en'));
which you can then use to parse a localized number with a known locale
const { decimal, group } = localeSeparators('en');
const localizedNumber = '52,000.50';
const groupRemoved = localizedNumber.replace(group, '');
const parsed = Number(groupRemoved);
// logs `52000.5`
console.log(parsed);