Question

I need to convert string to float, but there can be different input string formats, such as '1234,5' or '1234.5' or '1 234,5' or '1,234.5' or whatever. And I can not change locale decimal pointer or thousands separator, because I may not know what data I will get in advance.

Is there a way or method or library to parse and convert to float this kind of locale-specific values without knowing which locale is used?

P.S. Is there any solution exists for the same problem with dates?

TIA.

Was it helpful?

Solution

You can make some assumptions on which character is the thousands separator and which is the decimal point. However, there is a case where you cannot know for sure what do do:

  • Look for the last character that is . or ,. If it occurs more than once, the number does not have a decimal point and that character is the thousands separator
  • If the string contains exactly one of each, the last one is the decimal point
  • If the string contains only one point/comma, you are pretty much out of luck: 123.456 or 123,456 might be the number 123456 or 123.456. However, with a number like 123.45 - i.e. the number of digits after the potential thousands separator not being a multiple of three - you can assume that it's a decimal point.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top