Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String with Dot or Comma to Float Number

Tags:

java

I always like input in my function to get numbers that range from 0.1 to 999.9 (the decimal part is always separated by '.', if there is no decimal then there is no '.' for example 9 or 7 .

How do I convert this String to float value regardless of localization (some countries use ',' to separate decimal part of number. I always get it with the '.')? Does this depend on local computer settings?

like image 938
Dayanne Avatar asked Mar 08 '11 13:03

Dayanne


1 Answers

The Float.parseFloat() method is not locale-dependent. It expects a dot as decimal separator. If the decimal separator in your input is always dot, you can use this safely.

The NumberFormat class provides locale-aware parse and format should you need to adapt for different locales.

like image 176
sudocode Avatar answered Sep 23 '22 14:09

sudocode