Two different exits from Math.round (double * Math.pow (10, int))

I get a very strange problem. I get two different outputs from the same operation. The problem is described here.

double num = 2.0170818E7; 
int dp = 4;

String s = (Math.round(num * Math.pow(10, dp)) / (int) Math.pow(10, dp)) + "";

When I run the above code set in Android 5.0+, I get the output as:

The correct conclusion:

20170818

When I run the above code set under Android 5.0 (I tried with version 4.4.2), I get the output as:

Invalid output:

20172835

Correct conclusion: 20170818or expected conclusion. Why am I getting this strange problem?

+4
source share
4 answers

BigDecimal implementation:

    double num = 2.0170818E7; 
    int dp = 4;
    BigDecimal pow = new BigDecimal(Math.pow(10, dp));
    BigDecimal bigDecimal = new BigDecimal(num);
    BigDecimal result = bigDecimal.multiply(pow);
    result = result.divide(pow);
    String s = result.toString();
+2
source

Android jdk 6. , Android Studio 0.3.2 2013 . 7 , Android 5.0 . java 8.

JDK 8 DecimalFormat JDK-7131459: DecimalFormat (), .

, JDK-8039915: NumberFormat.format() HALF_UP , 5. :

99.9989 -> 100.00
99.9990 ->  99.99

Oracle Java 8 40

  • 8039915 OpenJDK [ Java 9] [JDK9patch]
+7

[ Android-, ...]

Math.pow(10,dp). (, 9999.999999 , . , int 9999 10000.

static final int[] POWERS = {1, 10, 100, 1000, 10000 ... } POWERS[dp] Math.pow(10,dp). .

, , Math.pow() , .

0

"" , Java. , . , , . Java, "double" "float" ( int), . , , , strictfp ( Java strictfp, Android).

0

Source: https://habr.com/ru/post/1684015/


All Articles