-5

I need to convert String to primitive float without losing decimal points.

Ex : String s = "11.50"; need to be converted as primitive float as 11.50f without losing decimal points in Java. Any help is appreciated. I want only float only. Its not for printing purpose. Its to store in DB.

azro
  • 53,056
  • 7
  • 34
  • 70
RaoPotla
  • 107
  • 2
  • 13
  • 1
    If you are converting it to float, why do you need the trailing zero? It's the same number without it – Rabbit Guy Aug 08 '17 at 16:22
  • 2
    Possible duplicate of [Convert string to float?](https://stackoverflow.com/questions/8705017/convert-string-to-float) –  Aug 08 '17 at 16:23
  • 3
    A float number is a _number._ It does not have a number of trailing decimals. As far as Java is concerned, `11.5` and `11.50` are exactly the same. Java will not save the extra zero. There is no way to make it save the extra zero. – Louis Wasserman Aug 08 '17 at 16:27

1 Answers1

1

Float.parseFloat(String) or Float.valueOf(String) can be used here.

But Float.parseFloat(String) is recommended because it returns a primitive float but Float.valueOf returns a Float object.

FYI, if you need exact precision while monetary calculations we should not use float or double either in place of that we should use BigDecimal.

user2862544
  • 415
  • 3
  • 13