double の 0.1 と BigDecimal? の 0.1 を 10000 回加算するのを 10000 回実行してみた
package com.snail.javaexam;
import java.math.BigDecimal;
public class App {
public static void main( String[] args ) {
long start = System.currentTimeMillis();
for (int cnt = 0; cnt < 10000; cnt++) {
fpCalc();
}
long end = System.currentTimeMillis();
System.out.println("FLOATING POINT ADD");
System.out.println(" ANS =" + fpCalc());
System.out.println(" TIME=" + (end - start));
start = System.currentTimeMillis();
for (int cnt = 0; cnt < 10000; cnt++) {
decimalCalc();
}
end = System.currentTimeMillis();
System.out.println("DECIMAL ADD");
System.out.println(" ANS =" + decimalCalc());
System.out.println(" TIME=" + (end - start));
}
private static double fpCalc(){
double ans = 0.0;
for(int cnt = 0; cnt < 10000; cnt++) {
ans += 0.1;
}
return ans;
}
private static BigDecimal decimalCalc() {
BigDecimal ans = new BigDecimal("0");
for(int cnt = 0; cnt < 10000; cnt++) {
ans = ans.add(new BigDecimal("0.1"));
}
return ans;
}
}
FLOATING POINT ADD ANS =1000.0000000001588 TIME=162 DECIMAL ADD ANS =1000.0 TIME=13169
double d = 0.123; double flooring = ((double)((long)(d * 10.0))) / 10.0;