-1

I'm trying to get a String, force it fo be a float, then format it in a way just as "###.##" (wich i can do it) and finally send it to a float variable (this is where I'm having an issue).

When I use Float.parseFloat() on that variable my float have a format "###.#" and I need the format of the float to be exactly "###.##" even if the original string is "321".

    String priceLabel = "321";
    float priceLabelConvertedInFloat = Float.parseFloat(priceLabel);
    System.out.println(priceLabelConvertedInFloat);

    NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
    DecimalFormat df = (DecimalFormat)nf;
    df.setMaximumFractionDigits(2);
    df.setMinimumFractionDigits(2);

    String priceStringWith2Decimals = df.format(priceLabelConvertedInFloat);
    System.out.println(priceStringWith2Decimals);

    float finalPrice = Float.parseFloat(priceStringWith2Decimals);
    System.out.println(finalPrice);

It prints "321.0" -> expected / "321.00" -> expected / "321.0" -> not desired :(

Thank you for any help you can provide.

  • A float does not have decimal digits, and it doesn't keep track of trailing zeros in the fractional part, even for binary fractional digits. You should always use a NumberFormat or `String.format` to output a float – Erwin Bolwidt Dec 21 '17 at 15:40

1 Answers1

3

You could change your final print statement to:

System.out.printf("%.2f", finalPrice);
achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • You may want to add a newline to that, to make it act like System.out.println: `"%.2f%n"` – VGR Dec 21 '17 at 16:03