0

I need to convert a string to Decimal() in Python, but it can have the characters "." and "," because of the Brazilian format, it could be something like "80.255,00". I used the string's replace() method like this str_value = str_value.strip().replace (". "," ").replace (", ",". ") and then converted it to Decimal like this value = Decimal(str_value), but I was wondering if there is a pythonic way of doing this, because using replace twice and then Decimal doesn't seem like the most beautiful way to do this, besides if the string is wrong like "80,255,00", "80,255.00" or "80.255.00" this will not work correctly :( In addition, the value may have more places after the comma, such as "80.255,0045".

Thanks to anyone who helps me

Patterson
  • 326
  • 1
  • 7
  • 19
  • Don't replace anything. It will never work. *Parse* the string using the correct regional settings. Half the world uses `,` as the decimal separator, China and India use `.` (the US does too, but that's 1/10th of the other two). If you try to replace separators you have at least a 50% chance to get it wrong resulting either in errors or worse, wrong results – Panagiotis Kanavos Apr 01 '21 at 10:22
  • You can use either `locale.atof` or a library like `babel` to parse a string using a specific locale, with eg `parse_decimal('1.099,98', locale='de')` – Panagiotis Kanavos Apr 01 '21 at 10:32
  • https://stackoverflow.com/questions/1779288/how-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-thousands-separato This post has similar problem. – Star Rider Apr 01 '21 at 10:36
  • Thank you very much, you guys helped me a lot. – Patterson Apr 01 '21 at 11:23

0 Answers0