Question

I have a double d and want to make it into a double with a limited amount of decimals (l).

Which code is "better"?

double d = 81.2384;
double l1 = d - d % 0.1;
double l2 = (int) (d * 10) * 0.1;

I would also like to be able to use this to only allow half numbers (e.g. 9.5612 -> 9.5).

Was it helpful?

Solution

Both solutions are acceptable. However, it is interested question, so I tried to compute proccesing time using this code :

    double d = 81.2384;
    double l1 = 0, l2 = 0;
    Long start = System.nanoTime();

    for (int i = 0; i < 1000 * 1000 * 100; i++) {
        l1 = d - d % 0.1;
    }
    Long time = System.nanoTime();
    Long l1speed = time - start;
    for (int i = 0; i < 1000 * 1000 * 100; i++) {
        l2 = (int) (d * 10) * 0.1;
    }
    Long l2speed = System.nanoTime() - time;

    System.out.println(l1 + l2); //to be sure that compiler does not ignore l1, l2
    System.out.println("computing l1 runs :" + ((double)l1speed / l2speed)+"faster than computing l2");

Which has this output :

computing l1 is: 76933.22854225677 times slower than computing l2

OTHER TIPS

You can use a DecimalFormat:

double d = 81.2384;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

which will print:

81.23
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top