exceltior
exceltior

Reputation: 103

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 ...

Upvotes: 2

Views: 2663

Answers (4)

Khalid Saeed
Khalid Saeed

Reputation: 156

For someone looking full decimal handling:Kotlin

fun validateNumber(number: String): String {
        return if (number.contains(".") && number.length > 3+number.indexOf("."))
            number.substring(0, number.indexOf(".")+3)
        else if (number.contains(".")){
            number.substring(0, number.indexOf(".")+2)+"0"
        }else{
            "$number.00"
        }
    }

Upvotes: 0

Md. Sajedul Karim
Md. Sajedul Karim

Reputation: 7085

You can use bellow function:

import java.text.DecimalFormat;
import java.math.RoundingMode;


public static double formatValue(Double number) {
        DecimalFormat df = new DecimalFormat("####0.00");

        df.setRoundingMode(RoundingMode.DOWN);
        return Double.parseDouble(df.format(number));
    }

Input = 31.6227890 , OutPUT = 31.62

Upvotes: 0

DanW
DanW

Reputation: 247

Thats what you want:

String number = "-9.22841";
DecimalFormat formatter = new DecimalFormat("0.00"); 
formatter.setRoundingMode(RoundingMode.DOWN); 
number = formatter.format(Double.valueOf(number));
System.out.println(number);

The output will be:

-9,22

Upvotes: 2

headlikearock
headlikearock

Reputation: 695

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);

Upvotes: 2

Related Questions