如何将整数值转换为小数值?

发布于 2024-09-19 08:35:56 字数 170 浏览 5 评论 0原文

我有一个整数值:

Integer value = 56472201;

该值可以是正数或负数。

当我将该值除以 1000000 时,我希望得到 56.472201 形式的结果,但它只给出商。我怎样才能同时获得商和余数?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

↙厌世 2024-09-26 08:35:56

将其转换为浮动,然后执行此操作:

int i = 56472201;

float j = ((float) i)/1000000.0

编辑:由于精度(您的情况需要),请使用双精度。同样正如 Konrad Rudolph 所指出的,不需要显式转换:

double j = i / 1000000.0;

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:

double j = i / 1000000.0;
九厘米的零° 2024-09-26 08:35:56

您必须首先将值转换为浮点类型,否则您将进行整数除法。

C# 中的示例:(

int value = 56472201;
double decimalValue = (double)value / 1000000.0;

此代码中实际上不需要强制转换,因为除以浮点数会将值强制转换为匹配,但在代码中写出强制转换会更清楚,因为这就是实际发生的情况。)

You have to convert the value to a floating point type first, otherwise you will be doing an integer division.

Example in 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.)

残月升风 2024-09-26 08:35:56

如果将 int 除以 double,将得到 double 结果,如本单元测试所示。

@Test
public void testIntToDouble() throws Exception {
    final int x = 56472201;
    Assert.assertEquals(56.472201, x / 1e6d);
}

1e6d1 * 10^6 表示为双精度数

If you divide an int by a double you will be left with a double result as illustrated by this unit test.

@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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文