如何在 Java 中将 $1319.2295689273974 舍入为 1319.23?
How can I round $1319.2295689273974 to 1319.23 in Java?
我正在做一个按月付款的项目,但我无法将金额精确到小数点后两位。我是编码新手,不知道这里是否遗漏了一些明显的东西。
这是我的代码:
double monthlyP = (1 + monthlyRate);//P = Payment
double power = Math.pow(monthlyP, numMonths);
monthlyP = power * monthlyRate;
double monthlyP2 = power - 1;
double FmonthlyP = (monthlyP/monthlyP2) * principle;//F = final
FmonthlyP = (FmonthlyP * 100)/Math.round(100);
一直输出1319.0 insted .23。我试过将 Math.round 放在乘法部分的前面和后面,但我无法让它工作。
计算机使用 64 位来表示一个 double
。 64 位,因此可以准确地容纳 2^64
个不同的值。
呃。
因为有无数个数字,所以这是个大问题。这意味着大多数(实际上是无限数量的)数字 根本无法用双精度表示。那么 java 是做什么的呢?它会默默地将事物四舍五入到它可以表示的最接近的祝福数字。
这样做的结果是,使用 double
作为货币是 一个大错误。
不要那样做。
最简单的方法是使用 long
,并代表您正在使用的货币数量的原子单位。美元和欧元的美分。 satoshi 代表比特币。
然后您的代码根据 'cents'(或 satoshis 或诸如此类)执行所有操作。当你 'render' 你的美分给用户时,通过格式化功能将其抛出。现在整个 'how do I round' 问题都没有实际意义了。
格式化函数示例:
public static String printEuro(long cents) {
boolean negative = cents < 0;
if (negative) cents = -cents;
int wholes = cents / 100;
int parts = cents % 100;
return String.format("%s€%d.%02d", negative ? "-" : "", wholes, parts);
}
注意:long 也是 64 位的,但是 double 需要能够表示,比如说,1e300
,或 0.000123
,而 long 则不能。如果我们谈论的是欧元,只要欧元总金额不超过 18 位,多头就可以覆盖所有美分。甚至整个国家每个世纪的 GDP 也没有那么高。如果您真的需要走那么远,请尝试 BigInteger
.
尝试使用
DecimalFormat df = new DecimalFormat("#.##");
完整文档here
我正在做一个按月付款的项目,但我无法将金额精确到小数点后两位。我是编码新手,不知道这里是否遗漏了一些明显的东西。
这是我的代码:
double monthlyP = (1 + monthlyRate);//P = Payment
double power = Math.pow(monthlyP, numMonths);
monthlyP = power * monthlyRate;
double monthlyP2 = power - 1;
double FmonthlyP = (monthlyP/monthlyP2) * principle;//F = final
FmonthlyP = (FmonthlyP * 100)/Math.round(100);
一直输出1319.0 insted .23。我试过将 Math.round 放在乘法部分的前面和后面,但我无法让它工作。
计算机使用 64 位来表示一个 double
。 64 位,因此可以准确地容纳 2^64
个不同的值。
呃。
因为有无数个数字,所以这是个大问题。这意味着大多数(实际上是无限数量的)数字 根本无法用双精度表示。那么 java 是做什么的呢?它会默默地将事物四舍五入到它可以表示的最接近的祝福数字。
这样做的结果是,使用 double
作为货币是 一个大错误。
不要那样做。
最简单的方法是使用 long
,并代表您正在使用的货币数量的原子单位。美元和欧元的美分。 satoshi 代表比特币。
然后您的代码根据 'cents'(或 satoshis 或诸如此类)执行所有操作。当你 'render' 你的美分给用户时,通过格式化功能将其抛出。现在整个 'how do I round' 问题都没有实际意义了。
格式化函数示例:
public static String printEuro(long cents) {
boolean negative = cents < 0;
if (negative) cents = -cents;
int wholes = cents / 100;
int parts = cents % 100;
return String.format("%s€%d.%02d", negative ? "-" : "", wholes, parts);
}
注意:long 也是 64 位的,但是 double 需要能够表示,比如说,1e300
,或 0.000123
,而 long 则不能。如果我们谈论的是欧元,只要欧元总金额不超过 18 位,多头就可以覆盖所有美分。甚至整个国家每个世纪的 GDP 也没有那么高。如果您真的需要走那么远,请尝试 BigInteger
.
尝试使用
DecimalFormat df = new DecimalFormat("#.##");
完整文档here