在搜索高效的手勢檢測代碼時,我偶然發現了一個函數,該函數將十進制數轉換爲由Google編寫的示例程序中的char數組。它完美地滿足了我的需求。
原代碼可以在這裏找到:http://developer.android.com/training/gestures/index.html(點擊「嘗試一下」右側下載包含項目的zip)
我在這裏複製的相關功能,以防萬一。
private static final int POW10[] = {1, 10, 100, 1000, 10000, 100000, 1000000};
/**
* Formats a float value to the given number of decimals. Returns the length of the string.
* The string begins at out.length - [return value].
*/
private static int formatFloat(final char[] out, float val, int digits) {
boolean negative = false;
if (val == 0) {
out[out.length - 1] = '0';
return 1;
}
if (val < 0) {
negative = true;
val = -val;
}
if (digits > POW10.length) {
digits = POW10.length - 1;
}
val *= POW10[digits];
long lval = Math.round(val);
int index = out.length - 1;
int charCount = 0;
while (lval != 0 || charCount < (digits + 1)) {
int digit = (int) (lval % 10);
lval = lval/10;
out[index--] = (char) (digit + '0');
charCount++;
if (charCount == digits) {
out[index--] = '.';
charCount++;
}
}
if (negative) {
out[index--] = '-';
charCount++;
}
return charCount;
}
不,不是。 'valueOf(double)'總是創建一個新的String(就像'「」+ double')一樣。這實際上是一個性能問題嗎? 'String.format' *如果還有*其他*字符串操作也可能是有益的。 – user2246674
您是否試過簡單的'「」+ doubletype' – Craig
請按照這些問題的答案。它已被詢問 http://stackoverflow.com/questions/10553710/fast-double-to-string-conversion-with-given-precision http://stackoverflow.com/questions/15176800/java-most-efficient- way-to-convert-string-to-double –