Search code examples
javainputstring-formatting

Formating a number to two decimals without rounding up and converting to Double


I know this has been questioned alot of times but i tried all solutions in other threads and i cant find one that matches what i want ...

So i have one input something like this -9.22841 which is read as a String, what i want to do is to format this number to two decimals like this -9.23 without rounding it up and then converting it to double without losing this format...

I have tried many ways like String.format("%.2f",number) and the one below ...

  String l = -9.22841
  DecimalFormat df = new DecimalFormat("#,00");
  String tmp =df.format(l);
  double t = Double.parseDouble(tmp);

and this one:

  String l = -9.22841
  DecimalFormat df = new DecimalFormat("#.00");
  String tmp =df.format(l);
  double t = Double.parseDouble(tmp);

but everytime i try to convert to double in the String.format("%.2f",number) or DecimalFormat df = new DecimalFormat("#.00"); gives error converting to double

and when i do this :

DecimalFormat df = new DecimalFormat("#,00");

The output is wrong and is something like this -9.23 where it should be -9.22

Thanks for your time ...


Solution

  • You could just chop off the String two spaces after the decimal:

    String number = "-9.22841";
    String shorterNumber = number.substring(0, number.indexOf(".")+3);
    double t = Double.parseDouble(shorterNumber);
    System.out.println(t);