Java 如何将整数值转换为十进制值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3707731/
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
How can i convert Integer value to decimal value?
提问by jimmy
i have an Integer value:
我有一个整数值:
Integer value = 56472201;
Where the value could be positive or negative.
值可以是正数或负数。
When I divide the value by 1000000, I want this result in the form 56.472201
but instead it gives me just the quotient. How am I able to get both the quotient and remainder values?
当我将值除以 1000000 时,我希望在表单中得到这个结果,56.472201
但它只给我商。我怎样才能获得商和余数?
采纳答案by lalli
cast it to float and then do it:
将其转换为浮动,然后执行以下操作:
int i = 56472201;
float j = ((float) i)/1000000.0
Edit: Due to precision(needed in your case), use double. Also as pointed by Konrad Rudolph, no need for explicit casting:
编辑:由于精度(在您的情况下需要),请使用双精度。同样正如 Konrad Rudolph 所指出的,不需要显式转换:
double j = i / 1000000.0;
回答by Guffa
You have to convert the value to a floating point type first, otherwise you will be doing an integer division.
您必须先将值转换为浮点类型,否则您将进行整数除法。
Example in C#:
C# 中的示例:
int value = 56472201;
double decimalValue = (double)value / 1000000.0;
(The cast is actually not needed in this code, as dividing by a floating point number will cast the value to match, but it's clearer to write out the cast in the code as that is what actually happens.)
(此代码中实际上不需要强制转换,因为除以浮点数会将值强制转换为匹配,但在代码中写出强制转换会更清楚,因为这就是实际发生的情况。)
回答by Jon Freedman
If you divide an int by a double you will be left with a double result as illustrated by this unit test.
如果将 int 除以 double,则会得到 double 结果,如本单元测试所示。
@Test
public void testIntToDouble() throws Exception {
final int x = 56472201;
Assert.assertEquals(56.472201, x / 1e6d);
}
1e6d
is 1 * 10^6
represented as a double
1e6d
被1 * 10^6
表示为双