-2

I want to convert the string to float with out losing it's precision.

String str = "140000.01";
float val = Float.valueOf(str);

Here, I'm getting the output i.e float value as 140000.02, is there any way to convert it into float without losing precision.

preetk
  • 189
  • 4
  • 12
  • 1
    Use double, double val = Double.parseDouble(str); – arifng Sep 03 '19 at 10:03
  • 1
    you can also use BigDecimal for getting correct value. `String str = "140000.01"; BigDecimal d = new BigDecimal(str).setScale(2);` – K Kishore Kumar Reddy Sep 03 '19 at 10:08
  • No, I can't use any other data type other than float. – preetk Sep 03 '19 at 10:19
  • 1
    @preetk Then you can't get the precision you want. `float` doesn't have it. Make up your mind. – user207421 Sep 03 '19 at 10:20
  • 1
    140000.01 is between two possible `float` values, 140000 and 140000.015625. 140000.015625 is closer, so it is the correct conversion. The shortest string that would convert to it is "140000.02". To get any closer to your original input you need to use a different data type, not `float`. – Patricia Shanahan Sep 03 '19 at 11:02
  • This is a case of There Ain't No Such Thing As A Free Lunch. If you are going to map the entire real line and some NaNs into 4294967296 bit patterns, most numbers you want are not going to be exactly representable. – Patricia Shanahan Sep 03 '19 at 13:24

1 Answers1

1

Simple way you can use double, like this:

String str = "140000.01";
double val = Double.parseDouble(str);
frianH
  • 7,295
  • 6
  • 20
  • 45