108

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

Johnny
  • 1,239
  • 3
  • 12
  • 13

16 Answers16

156

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;
eshimoniak
  • 740
  • 2
  • 12
  • 36
Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
46
DecimalFormat df = new DecimalFormat(fmt);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);

Check available RoundingMode and DecimalFormat.

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
Cedric Dubourg
  • 469
  • 4
  • 2
  • Does not address the Question, which asked for truncation rather than rounding. – Basil Bourque Apr 14 '15 at 19:56
  • 8
    @BasilBourque RoundingMode.DOWN is truncation. Compare with other answers that incorrectly recommend floor functions (floor only truncates positive numbers), this works correctly for both positive and negative values. – Dev May 28 '15 at 19:09
  • 1
    @Dev I stand corrected. I see now that `DOWN` does indeed have the effect of truncation for both positive and negative numbers. As seen in examples table in [the doc](https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html). – Basil Bourque May 28 '15 at 20:42
25

Bit Old Forum, None of the above answer worked for both positive and negative values ( I mean for the calculation and just to do truncate without Rounding). From the 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
Community
  • 1
  • 1
Mani
  • 2,964
  • 2
  • 13
  • 24
9

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.

Michael Borgwardt
  • 327,225
  • 74
  • 458
  • 699
7

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

phuclv
  • 27,258
  • 11
  • 104
  • 360
Tarvis
  • 71
  • 1
  • 1
  • 3
    This is a *terrible* general solution. Both the multiply and the cast will end up throwing away data and resulting in what are effectively random numbers if `unroundedNumber` is big enough. It may work for the example in the question, but a general solution should work for any `double`. – blm Nov 14 '15 at 07:35
6

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.

Jao Assy
  • 77
  • 2
  • 6
5

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
Rushdi Shams
  • 2,373
  • 17
  • 29
3

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!

Ankush G
  • 771
  • 6
  • 13
3

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

Vlad
  • 33,616
  • 5
  • 74
  • 185
1

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;
spenibus
  • 4,079
  • 11
  • 23
  • 33
0

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;
}
chris31389
  • 5,798
  • 2
  • 44
  • 55
0
      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);
  • Welcome to StackOverflow and congratulations on your first answer. While the code you posted may address the question asked by the original poster, you should add a few sentences to explain how your solution is better or more suited than the (many) other answers for some specific situations. – Patrick Dec 31 '20 at 14:26
0

Maybe following :

double roundTwoDecimals(double d) { 
      DecimalFormat twoDForm = new DecimalFormat("#.##"); 
      return Double.valueOf(twoDForm.format(d));
}  
Ritesh Mengji
  • 5,356
  • 8
  • 28
  • 46
-1

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
Community
  • 1
  • 1
HolyLance
  • 21
  • 4
-2

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.

Rainbow975
  • 37
  • 2
  • 1
    The original question is about truncating, not rounding. Also, converting a double to a long won't work well at all if the double is large enough. – blm Nov 14 '15 at 07:27
-2
//if double_v is 3.545555555
String string_v= String.valueOf(double_v);
int pointer_pos = average.indexOf('.');//we find the position of '.'
string_v.substring(0, pointer_pos+2));// in this way we get the double with only 2 decimal in string form
double_v = Double.valueOf(string_v);//well this is the final result

well this might be a little awkward, but i think it can solve your problem :)

  • This code gets the job done, but it’s not elegant and has poor performance. It might be okay in school projects, but definitely not a solution someone would use in production for any system, unless you want to have headaches later on. – cbaldan Mar 06 '19 at 00:29