Rounding in Java

Rounding in Java

Today I’ve got a defect from QA which deals with the rounding. During the fix of it, I’ve decided to measure which way of rounding is the fastest one. I’ve got several in my mind, so I’ve wrote a small test which measures time. Three approaches(iterations: 10.000.000, accuracy: 3 digits, value: 3.1574454353) have been tested out.

My laptop configuration:
1. Fedora 11 i686
2. Sun JDK 1.6.0.16
3. CPU: Intel Core 2 Duo P7350 @ 2.00GHz
4. RAM: 3 GB

I’ve used the following approaches:

1. BigDecimal conversion:

2. DateFormat conversion:

3. Division/multiplication combination:

Please find the results in milliseconds below:

BigDecimal Conversion DecimalFormat Conversion Division/ multiplication
Iteration 1 21823 19140 525
Iteration 2 20898 19120 502
Iteration 3 22330 19558 483
Average 21683.67 19272.67 503.33

The results are vivid. Simple mathematical calculations are incredibly faster than other approaches. The funny thing here is that BigDecimal/DecimalFormat approaches are proposed on various forums while they’re really slow.