2

if input = 31.6227890 then output = 31.6227 but the output is coming as 31.6228

HMT
  • 2,093
  • 1
  • 19
  • 51

5 Answers5

4

You can use below function:

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

public static double formatValue(Double number) {
        DecimalFormat df = new DecimalFormat("####0.0000");
        return Double.parseDouble(df.format(number));
    }

Edit : you have to add below code for rounding off.

df.setRoundingMode(RoundingMode.DOWN);

Input = 31.6227890

Output = 31.6227

Anubhav Singh
  • 8,321
  • 4
  • 25
  • 43
Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87
2

If you want to round down, you can use truncation like this.

double d = 31.6227890;
d = ((long) (d * 10000)) / 10000.0; // truncates down to 0
System.out.println(d);

prints

31.6227

Note: this might print less than 4 digits. If you always want 4 you need to use formatting.

d = 31.60007890;
d = ((long) (d * 10000)) / 10000.0; // truncates down to 0
System.out.println(d);
System.out.printf("%.4f%n", d);

prints

31.6
31.6000

NOTE: For large values you wouldn't round them as this would result in an overflow.

private static final double WHOLE_NUMBER = 1L << 53;
public static double trunc4(double d) {
    final double factor = 1e4;
    return Math.abs(d) >= WHOLE_NUMBER / factor 
           ? d 
           : ((long) (d * factor)) / factor;
}

The point at which you get an error is for numbers so large they are whole numbers anyway (due to the limits of the precision on double)

NOTE: If you used float the limit at which you would get a precision error is for much smaller values.

double d = 1024.00039999;
float f= (float) (long) (d * 10000) / 10000;
System.out.println(f);

prints

1024.0002
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    There's the usual fp inaccuracies to deal with it you want more decimal places. This will also not work correctly for large values of d (i.e. we use accuracy and risk overflows). For"normal" values this will be fine though – Voo Jul 19 '18 at 06:50
1

You can round down using a BigDecimal:

new BigDecimal(31.6227890d).setScale(4, RoundingMode.DOWN)

That returns the desired result: 31.6227.

For a double, you can use .doubleValue():

new BigDecimal(31.6227890d).setScale(4, RoundingMode.DOWN).doubleValue()
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Note `System.out.println(new BigDecimal(0.0003d).setScale(4, RoundingMode.DOWN));` prints `0.0002` I suspect `BigDecimal.valueOf(...)` would be better. – Peter Lawrey Jul 19 '18 at 07:20
0

float i=(float)((int) (31.6227890 *10000))/10000;

System.out.println(i);

subbu
  • 254
  • 2
  • 7
0

You can multiply it per 1000, use Math.floor() and divide it per 1000

    double a = 10.345665654;
    double b = Math.floor(a * 10000) / 10000;
    System.out.println(b);
Kaostias
  • 321
  • 4
  • 24