0

我需要显示很多货币(欧元)值,这些值在使用滑块时可能会发生变化。因此,我创建了一个更快的 Double to Euro函数,而不是使用数字格式化程序(无需内部化,在资源有限的 android 设备上运行)。

虽然这个函数比默认的数字格式化程序快得多,但如果它可以更快的话会很有趣。有什么创意吗?

/*
 * Ugly but fast double to euro string function
 */
public static final String getEuroString(Double euro) {
    if(euro == null) {
        return "0,00 €";
    }

    final double    d_euro  = euro;
    final int       post    = Math.abs((int) Math.round((d_euro % 1) * 100));

    return ((int) d_euro) + "," + (post < 10 ? "0" + post : post) + " €";
}
4

2 回答 2

0

如果您给出四舍五入或表示错误,您需要对结果进行四舍五入。

尝试

public static void main(String[] args) {
    System.out.println(print(70e12));
    System.out.println(print(70e12 + 0.01));
}

public static String print(double euro) {
    long eurocents = Math.round(euro * 100);
    String centsStr = Long.toString(100 + eurocents%100).substring(1);
    return eurocents / 100 + "," + centsStr + " €";
}

在https://ideone.com/NAonp0上打印

70000000000000,00 €
70000000000000,01 €

使用这种方法,您可以毫无错误地存储 70 万亿欧元。

于 2012-08-01T16:00:50.007 回答
0

不要使用双精度存储货币值,使用大十进制或joda-money.sourceforge.net

于 2012-08-01T15:58:19.253 回答