尝试在java中将double乘以int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22041593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to multiply double by int in java
提问by Edge
I am trying to multiply 1207.87 by 10000 and expecting 12078700.0 but I am getting 1.2078699999999998E7
我试图将 1207.87 乘以 10000 并期待 12078700.0 但我得到 1.2078699999999998E7
I understand that its related to precision mistake but how do i rectify this problem
我知道它与精度错误有关,但我该如何纠正这个问题
EDIT:-
编辑:-
I simply want to remove the decimal
我只想删除小数
采纳答案by mok
try this:
尝试这个:
1207.87f * 10000
the result will be:
结果将是:
1.20787E7
回答by m-szalik
This is because of float numbers representation.
You can:
这是因为浮点数表示。
你可以:
- round it
Math.round(...)
- or use BigDecimalif you need high precision.
- 圆它
Math.round(...)
- 或者如果您需要高精度,请使用BigDecimal。
More about What Every Computer Scientist Should Know About Floating-Point Arithmetic.
回答by m0skit0
You cannot rectify this if you use double
type. You can if you use BigDecimal
.
如果您使用double
类型,则无法纠正此问题。如果您使用BigDecimal
.
回答by Rahul Tripathi
You need to do the CAST:
您需要执行 CAST:
(int) 1207.87 * 10000
回答by Lucian Novac
Try to use decimal format like:
尝试使用十进制格式,如:
DecimalFormat f = new DecimalFormat("#0.00");
f.format(Double.valueOf(yourDouble));
Hope this can help you!
希望这可以帮到你!
回答by Lesto
double are stored in exponental precision in java and many other languages. see IEEE754for more information about float, double and their variant
double 在 java 和许多其他语言中以指数精度存储。有关 float、double 及其变体的更多信息,请参阅IEEE754
If you want a integer result, then cast your floating point number, or the result. If you want to just print a floating number in "ordinary notation", then you can use the class NumberFormat
如果你想要一个整数结果,然后转换你的浮点数,或者结果。如果您只想以“普通表示法”打印浮点数,则可以使用该类NumberFormat
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(4.0));
example taken from here
取自此处的示例
finally you can use a fixed precision number with the class BigDecimal, but please take care that this is normally not hardware (FPU) accelerated so will slow down a lot your calculation, but will give you fixed error. That kind of number is especially used in simulation where error must be know
最后,您可以使用 BigDecimal 类的固定精度数,但请注意,这通常不是硬件 (FPU) 加速,因此会大大减慢您的计算速度,但会给您带来固定错误。这种数字特别用于必须知道错误的模拟中
回答by Rahul
You can use formatted output as below:
您可以使用如下格式化输出:
double ans = 1207.87 * 10000;
System.out.printf("ans: %.0f\n", ans);
Output:
输出:
ans: 12078700
回答by user3355856
Simple way would be this one:
简单的方法是这个:
Double j = 1207.87;
int x = j.intValue();
System.out.println(x * 10000);