1

我有一个每隔几毫秒调用一次的函数,它需要将双精度数转换为字符数组、字符串或其他存储文本的方法。转换后立即使用 Android 的“canvas.drawText”函数将其写入屏幕。目前,我正在使用 String.valueOf(doubletype),但每次循环运行时都会分配一个新的 String 对象。

我想知道是否有另一种方法可以将此双精度转换为字符串或字符数组等,而无需在每次循环运行时分配和收集内存。我错过了一些明显的东西吗?

4

1 回答 1

1

While searching for efficient gesture detection code, I stumbled upon a function that converts decimal numbers to char arrays in an example program written by Google. It serves my needs perfectly.

The original code can be found here: http://developer.android.com/training/gestures/index.html (Click "try it out" on the right to download the zip containing the project)

I've copied the relevant function here, just in case.

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;
    }
于 2013-07-16T16:30:38.460 回答