-1

So basically i want my float number price (eg:- 20.0) to be 20.00, with an additional zero. So what i tried to do below here is first to add an extra zero, which results in converting it to a string and then convert it back to float because my object type needs to store it as 20.00 as a Float.

Float lowest = productDetail1.getProductSummary().getPrice().getLowest();
String lowestPrice = String.format("$%.2f", lowest);
  try {
    Float floatVal = Float.valueOf(lowestPrice).floatValue();
    productDetail1.getProductSummary().getPrice().setLowest(floatVal);
  }catch (NumberFormatException e){
    LOGGER.error("Number Format Exception " + e.getMessage());
  }

So i debugged it, and i found out that the first 2 lines of codes work fine, but an error is thrown at line 3 :-

Float floatVal = Float.valueOf(lowestPrice).floatValue();

The error im getting is :- java.lang.numberformatexception for input string : "$10.00"

I hope someone can help me with this. A written code example will be helpful as a solution.

7
  • There is a dollar sign in your lowestPrice. Commented Oct 20, 2020 at 7:04
  • 3
    why you need it to be .00 as float? it is just a display, you can convert it with %.2f at display time Commented Oct 20, 2020 at 7:04
  • @Greedo I need to display this in a html, where im sending this as a model.attribute, so yeah i need to convert it to .00 in java itself Commented Oct 20, 2020 at 7:12
  • 2
    20.0 and 20.00 are exactly the same float number. You can't have a float equal to 20.00 and not equal to 20.0. Now, "20.0" and "20.00" are different string representations of the same number. Commented Oct 20, 2020 at 7:21
  • Floating point has no precision (decimals after point) and are just an approximation, 1000*x where x is 0.1 will show an approximation error. And then there is that dollar character where you tripped over. Try BigDecimal. Commented Oct 20, 2020 at 7:26

1 Answer 1

1

It is not possible to parse $ as part of the number. You need to remove that from the String before parsing it.
For example

Float floatVal = Float.valueOf(lowestPrice.substring(1)).floatValue();
Sign up to request clarification or add additional context in comments.

3 Comments

ok so tried this, but still since i convert it back to float..the value becomes 20.0 again without being 20.00, u have any solution for that? @Turamarth
20.0 and 20.00 are exactly the same float number. You can't have a float equal to 20.00 and not equal to 20.0. Now, "20.0" and "20.00" are different string representations of the same number.
yeah thnx, but i had to create a bean class and send the value which is "20.00" as a string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.