How can I truncate a double to only two decimal places in Java?

JavaDoubleTruncateDecimalformat

Java Problem Overview


For example I have the variable 3.545555555, which I would want to truncate to just 3.54.

Java Solutions


Solution 1 - Java

If you want that for display purposes, use java.text.DecimalFormat:

 new DecimalFormat("#.##").format(dblVar);

If you need it for calculations, use java.lang.Math:

 Math.floor(value * 100) / 100;

Solution 2 - Java

DecimalFormat df = new DecimalFormat(fmt);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);

Check available RoundingMode and DecimalFormat.

Solution 3 - Java

None of the other answers worked for both positive and negative values ( I mean for the calculation and just to do "truncate" without Rounding). and without converting to string.

From the https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java link

private static BigDecimal truncateDecimal(double x,int numberofDecimals)
{
	if ( x > 0) {
		return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_FLOOR);
	} else {
		return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_CEILING);
	}
}

This method worked fine for me .

System.out.println(truncateDecimal(0, 2));
	System.out.println(truncateDecimal(9.62, 2));
	System.out.println(truncateDecimal(9.621, 2));
	System.out.println(truncateDecimal(9.629, 2));
	System.out.println(truncateDecimal(9.625, 2));
	System.out.println(truncateDecimal(9.999, 2));
	System.out.println(truncateDecimal(-9.999, 2));
	System.out.println(truncateDecimal(-9.0, 2));

Results :

0.00
9.62
9.62
9.62
9.62
9.99
-9.99
-9.00

Solution 4 - Java

Note first that a double is a binary fraction and does not really have decimal places.

If you need decimal places, use a BigDecimal, which has a setScale() method for truncation, or use DecimalFormat to get a String.

Solution 5 - Java

If, for whatever reason, you don't want to use a BigDecimal you can cast your double to an int to truncate it.

If you want to truncate to the Ones place:

  • simply cast to int

To the Tenths place:

  • multiply by ten
  • cast to int
  • cast back to double
  • and divide by ten.

Hundreths place

  • multiply and divide by 100 etc.

Example:

static double truncateTo( double unroundedNumber, int decimalPlaces ){
    int truncatedNumberInt = (int)( unroundedNumber * Math.pow( 10, decimalPlaces ) );
    double truncatedNumber = (double)( truncatedNumberInt / Math.pow( 10, decimalPlaces ) );
    return truncatedNumber;
}

In this example, decimalPlaces would be the number of places PAST the ones place you wish to go, so 1 would round to the tenths place, 2 to the hundredths, and so on (0 rounds to the ones place, and negative one to the tens, etc.)

Solution 6 - Java

Formating as a string and converting back to double i think will give you the result you want.

The double value will not be round(), floor() or ceil().

A quick fix for it could be:

 String sValue = (String) String.format("%.2f", oldValue);
 Double newValue = Double.parseDouble(sValue);

You can use the sValue for display purposes or the newValue for calculation.

Solution 7 - Java

You can use NumberFormat Class object to accomplish the task.

// Creating number format object to set 2 places after decimal point
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);            
nf.setGroupingUsed(false);

System.out.println(nf.format(precision));// Assuming precision is a double type variable

Solution 8 - Java

3.545555555 to get 3.54. Try Following for this:

    DecimalFormat df = new DecimalFormat("#.##");

	df.setRoundingMode(RoundingMode.FLOOR);

	double result = new Double(df.format(3.545555555);

This will give= 3.54!

Solution 9 - Java

Maybe Math.floor(value * 100) / 100? Beware that the values like 3.54 may be not exactly represented with a double.

Solution 10 - Java

Here is the method I use:

double a=3.545555555; // just assigning your decimal to a variable
a=a*100;              // this sets a to 354.555555
a=Math.floor(a);      // this sets a to 354
a=a/100;              // this sets a to 3.54 and thus removing all your 5's

This can also be done:

a=Math.floor(a*100) / 100;

Solution 11 - Java

Maybe following :

double roundTwoDecimals(double d) { 
      DecimalFormat twoDForm = new DecimalFormat("#.##"); 
      return Double.valueOf(twoDForm.format(d));
}  

Solution 12 - Java

A quick check is to use the Math.floor method. I created a method to check a double for two or less decimal places below:

public boolean checkTwoDecimalPlaces(double valueToCheck) {
	
	// Get two decimal value of input valueToCheck 
	double twoDecimalValue = Math.floor(valueToCheck * 100) / 100;
	
	// Return true if the twoDecimalValue is the same as valueToCheck else return false
	return twoDecimalValue == valueToCheck;
}

Solution 13 - Java

      double value = 3.4555;
      String value1 =  String.format("% .3f", value) ;
      String value2 = value1.substring(0, value1.length() - 1);
      System.out.println(value2);	      
      double doublevalue= Double.valueOf(value2);
      System.out.println(doublevalue);

Solution 14 - Java

I used Math.floor() method and basic moving of decimal places by (100 = 2).

//3.545555555 to 3.54 by floor method
double x = 3.545555555;
double y = Math.floor(x * 100); //354
double z = y / 100; //3.54

Solution 15 - Java

double firstValue = -3.1756d;

double value1 = (((int)(Math.pow(10,3)*firstValue))/Math.pow(10,3));

Solution 16 - Java

I have a slightly modified version of Mani's.

private static BigDecimal truncateDecimal(final double x, final int numberofDecimals) {
	return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_DOWN);
}

public static void main(String[] args) {
	System.out.println(truncateDecimal(0, 2));
    System.out.println(truncateDecimal(9.62, 2));
    System.out.println(truncateDecimal(9.621, 2));
    System.out.println(truncateDecimal(9.629, 2));
    System.out.println(truncateDecimal(9.625, 2));
    System.out.println(truncateDecimal(9.999, 2));
    System.out.println(truncateDecimal(3.545555555, 2));

    System.out.println(truncateDecimal(9.0, 2));
    System.out.println(truncateDecimal(-9.62, 2));
    System.out.println(truncateDecimal(-9.621, 2));
    System.out.println(truncateDecimal(-9.629, 2));
    System.out.println(truncateDecimal(-9.625, 2));
    System.out.println(truncateDecimal(-9.999, 2));
    System.out.println(truncateDecimal(-9.0, 2));
    System.out.println(truncateDecimal(-3.545555555, 2));
    
}

Output:

0.00
9.62
9.62
9.62
9.62
9.99
9.00
3.54
-9.62
-9.62
-9.62
-9.62
-9.99
-9.00
-3.54

Solution 17 - Java

This worked for me:

double input = 104.8695412  //For example

long roundedInt = Math.round(input * 100);
double result = (double) roundedInt/100;

//result == 104.87

I personally like this version because it actually performs the rounding numerically, rather than by converting it to a String (or similar) and then formatting it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnnyView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavaCedric DubourgView Answer on Stackoverflow
Solution 3 - JavaManiView Answer on Stackoverflow
Solution 4 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 5 - JavaTarvisView Answer on Stackoverflow
Solution 6 - JavaJao AssyView Answer on Stackoverflow
Solution 7 - JavaRushdi ShamsView Answer on Stackoverflow
Solution 8 - JavaAnkush GView Answer on Stackoverflow
Solution 9 - JavaVladView Answer on Stackoverflow
Solution 10 - JavaMitchell HynesView Answer on Stackoverflow
Solution 11 - JavaRitesh MengjiView Answer on Stackoverflow
Solution 12 - Javachris31389View Answer on Stackoverflow
Solution 13 - JavaAntip AlexView Answer on Stackoverflow
Solution 14 - JavaR.E.F.View Answer on Stackoverflow
Solution 15 - JavaCulloo AvineshView Answer on Stackoverflow
Solution 16 - JavaHolyLanceView Answer on Stackoverflow
Solution 17 - JavaRainbow975View Answer on Stackoverflow