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
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 ConversionDecimalFormat ConversionDivision/ multiplication
Iteration 12182319140525
Iteration 22089819120502
Iteration 32233019558483

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.