7

how can i convert "570.581,88" into an integer and sort accordingly?

2
  • A single integer? What's that comma doing there? Commented Dec 9, 2010 at 5:38
  • How will you convert "100.99" to an int? Commented Dec 9, 2010 at 5:40

2 Answers 2

12
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;
Sign up to request clarification or add additional context in comments.

1 Comment

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?
0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.