0

I have different numbers from 100.000 to 3.000.000 saved as a String. I Want to convert them into a number in exact the same format with the parsefloat function and sum them after it. With numbers under 1 million and only one dot it will working, with a number over one million it deletes the last numbers after the dot. for example when the productionItem.calculationResult.stromKwh = 1.358.149 the result it 1.358.

result is 1358.149 parseFloat(String(productionItem.calculationResult.stromKwh).replace('.','').replace(',','.'));

result is 1.358

parseFloat(String(productionItem.calculationResult.stromKwh).replace(',','.'));
  • 3
    You should really only have the display format when presenting it to a user, but your internal datastructures should just have the float itself – Icepickle Aug 13 '19 at 09:14
  • To add to what Icepickle said, check out: https://blog.abelotech.com/posts/number-currency-formatting-javascript/ With those functions you can easily display the number how you want to. – claasic Aug 13 '19 at 09:19
  • @assoron but are they also converting with the functions to a integer? i tested it but i still cant add the numbers. but already the format is correct. – Lukas Kollin Aug 13 '19 at 09:38
  • The point is that as long as you are not presenting your values to the user, don't change them. Integer and Float will cause you problems down the lines when you stylize them. Instead the moment you want to present the values, you change them into a pretty String! – claasic Aug 13 '19 at 09:56

1 Answers1

0

First of all you need to understand that different locales use different number formatting characters. In english locales, decimals are separated using a dot (3.14159265) and thousands are separated using commas (1,000,000 is a million).

In german locales, these are reversed. Your numbers are formatted according to german locale rules.

Programming languages almost always use english locale conventions but without thousands separators. The dot is interpreted as the decimal point. parsefloat() parses numbers as JavaScript would do it, using the dot as the decimals separator.

Sadly, JavaScript has locale-specific number formatting (toLocaleString()) but no corresponding parsing functions. There are libraries which provide these, have a look at How do I convert String to Number according to locale (opposite of .toLocaleString)? for a discussion.