Java - 如何从整数(金钱)中获取双精度数
我得到:
int number = 1255; -> //It could also be 125(1€25Cent) or 10(10Cent) or 5(5Cent)
public double toMoney(int number)
{
...
}
作为返回,我想要双数:12.55或者如果输入:10则:00.10
我知道我可以用 Modulo 做这样的事情:
1255 % 100 .. 得到 55.. 但是如何做到 12 最后,如何 将其形成为双精度?
I got:
int number = 1255; -> //It could also be 125(1€25Cent) or 10(10Cent) or 5(5Cent)
public double toMoney(int number)
{
...
}
as return, I want the double number: 12.55 or if input: 10 then: 00.10
I know that I can do with Modulo something like this:
1255 % 100.. to get 55.. But how to do it for 12 and at the end, how to
form it as a double?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
该方法不应该存在,因为它无法给出正确的结果。
因为在内部,
double
是一种无法准确表示 0.1、0.2 等数字的格式(二进制浮点)或 0.3根本。请阅读浮点指南了解更多信息。如果需要小数,则输出格式应为
BigDecimal
或String
。That method should not exist, because it cannot give correct results.
Because internally,
double
is a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all. Read the Floating-Point Guide for more information.If you need decimals, your output format should be
BigDecimal
orString
.打印金额的方法是使用 NumberFormat 类!
查看此示例:
打印此输出:
您可以尝试不同的区域设置和货币代码。请参阅文档:http://download.oracle。 com/javase/1.4.2/docs/api/java/text/NumberFormat.html。
The way printing money amounts should be done is by using NumberFormat class!
Check out this example:
Which print this output:
You can try different locales and currency codes. See docs: http://download.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html.
如果我正确理解您的问题,您可能会尝试这样做:
尽管有一句警告: 由于舍入,您不应该使用浮点货币 -如果
您只想以货币格式打印数字,这里有一个 100% 安全的方法:
这可能可以更好地简化...当然您可以使用 BigDecimal,但在我看来,这打破了蚂蚁与一个大锤。
If I'm understanding your question correctly, you're probably trying to just do this:
Though a word of warning: You shouldn't be using floating-point for money due to round-off issues.
If you just want to print the number in money format, here's a 100% safe method:
This can probably be simplified a lot better... Of course you can go with BigDecimal, but IMO that's smashing an ant with a sledgehammer.
如果您处理的是货币金额,请记住,将数字转换为
双精度
时可能会出现一些精度损失。If you're dealing with monetary amounts, do bear in mind that some loss of precision can occur when you convert the number to a
double
.诀窍是使用
100.0
而不是100
来强制 java 使用双除法。The trick is to use
100.0
rather than100
to force java to use double division.PS 你不应该使用 double 来表示货币价值,这是个坏主意。
P.S. You shouldn't use double for money values, bad idea.