11

Having the following code in Java:

double operation = 890 / 1440;  
System.out.println(operation);  

Result: 0.0

What I want is to save the first 4 decimal digits of this operation (0.6180). Do you know how can I do it?

Bob
  • 5,510
  • 9
  • 48
  • 80
Eric
  • 317
  • 3
  • 6
  • 10
  • 2
    where do you want to "save" it? – Bozho Jul 02 '10 at 19:46
  • Operations on floating point numbers (float or double) gives not exact result, which makes them unsuitable for any financial calculation which requires exact result and not approximation. Use BigDecimal instead. – Andrey Dmitriev Nov 26 '16 at 01:00

7 Answers7

19

Initialize your variable with an expression that evaluates to a double rather than an int:

double operation = 890.0 / 1440.0;

Otherwise the expression is done using integer arithmetic (which ends up truncating the result). That truncated result then gets converted to a double.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • Although this is pretty, it may be worthwhile to instead (or as well) explicitly cast both numbers to doubles. The reason is that if someone (even the OP later on) comes in later and changes the numbers, they may forget to add the decimals and the functionality will mysteriously break. – Cam Jul 02 '10 at 20:09
  • I agree, Bozho's 123d solution is preferred as the intent clearer. – Steve Kuo Jul 02 '10 at 21:26
  • One of many gotchas. I personaly like to leave a little comment in that case. Something like: "Double literals must be used. Integer literals will result in integer arithmetics." It is always a little reminder why is this so. – f470071 Sep 17 '15 at 08:56
13

You can use the double literal d - otherwise your numbers are considered of type int:

double operation = 890d / 1440d;

Then you can use a NumberFormat to specify the number of digits.

For example:

NumberFormat format = new DecimalFormat("#.####");
System.out.println(format.format(operation));
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Does NumberFormat allow me to save four decimal digits in a variable or it only displays the first "X" decimal digits? – Eric Jul 02 '10 at 19:36
  • 2
    NumberFormat only affects the presentation, the variable 'operation' is not affected – Kennet Jul 02 '10 at 19:40
7

You can also do something like this:

double result = (double) 890 / 1400;

which prints the following:

0.6180555555555556

You can check how to round up the number here

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
  • 1
    Just remember, you're not casting (890/1440) to double with this. You're casting 890 to double with this. And a (double/int) operation returns a double. – corsiKa Jul 02 '10 at 20:08
  • Yeah. But I think that this method is a bit better since it also works when you have double variables instead of hard coded ones, at least, in C# I used to experience the same problem and fixed it as above. – npinti Jul 02 '10 at 21:18
6

This is done using BigDecimal

   import java.math.BigDecimal;
import java.math.RoundingMode;


    public class DecimalTest {

        /**
         * @param args
         */
        public static void main(String[] args) {
            double operation = 890.0 / 1440.0;
            BigDecimal big = new BigDecimal(operation);     
            big = big.setScale(4, RoundingMode.HALF_UP);        
            double d2 = big.doubleValue();
            System.out.println(String.format("operation : %s", operation));
            System.out.println(String.format("scaled : %s", d2));
        }
    }

Output

operation : 0.6180555555555556 scaled : 0.6181

Greg
  • 1,671
  • 2
  • 15
  • 30
2

BigDecimal, although very clumsy to work with, gives some formatting options:

    BigDecimal first = new BigDecimal(890);
    BigDecimal second = new BigDecimal(1440);
    System.out.println(first.divide(second, new MathContext(4, RoundingMode.HALF_EVEN)));
Kennet
  • 5,736
  • 2
  • 25
  • 24
1
double operation = 890.0 / 1440;
System.out.printf(".4f\n", operation);
ZZ Coder
  • 74,484
  • 29
  • 137
  • 169
0

If you really want to round to the first 4 fractional digits you can also use integer arithmetic by first multiplying the first number so its digits are shifted the right amount f places to the left:

long fractionalPart = 10000L * 890L / 1440L;

I'm using long here to avoid any overflows in case the temporary result does not fit in 32 bits.

Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118