Java – fast double string conversion with given precision
I need to convert double to string with the given precision String. Format ("%. 3F", value) (or decimalformat) executes the job, but the benchmark shows that it is not very fast double ToString conversion (about 1-3 seconds to convert 1 million numbers on my machine))
Is there a better way?
Updating: benchmark results
Random numbers range from 0 to 1000000, resulting in operations per millisecond (Java 1.7.0_45)
Benchmark Mean Mean error Units String_format 747.394 13.197 ops/ms BigDecimal_toPlainString 1349.552 31.144 ops/ms DecimalFormat_format 1890.917 28.886 ops/ms Double_toString 3341.941 85.453 ops/ms DoubleFormatUtil_formatDouble 7760.968 87.630 ops/ms SO_User_format 14269.388 168.206 ops/ms
Solution
Disclaimer: I only recommend that you use this speed is an absolute requirement
On my machine, the following can complete 1 million conversions in 130ms:
private static final int POW10[] = {1,10,100,1000,10000,100000,1000000}; public static String format(double val,int precision) { StringBuilder sb = new StringBuilder(); if (val < 0) { sb.append('-'); val = -val; } int exp = POW10[precision]; long lval = (long)(val * exp + 0.5); sb.append(lval / exp).append('.'); long fval = lval % exp; for (int p = precision - 1; p > 0 && fval < POW10[p]; p--) { sb.append('0'); } sb.append(fval); return sb.toString(); }
The code provided has several disadvantages: it can only handle limited doubles and does not handle Nan The former can be solved by expanding pow10 array (but only partially) The latter can be handled explicitly in the code