Java的VS.NET中 - 转换双为int时不同的答案答案、不同、VS、Java

2023-09-04 12:49:49 作者:爷有爷的范

在C#中,如果我想转换一个双(1.71472),以一个int然后我得到的答案2.如果我使用的intValue()方法做到这一点在Java中,我得到1作为回答。

In C# if I want to convert a double (1.71472) to an int then I get the answer 2. If I do this in Java using intValue() method, I get 1 as the answer.

难道Java的四舍五入的转换?

Does Java round down on conversions?

为什么在Java API文档有这样的信息很少有关它们的类,即

Why do the Java API docs have such scant information about their classes i.e.

返回指定的值   数为int。这可能涉及   舍入或截断。

Returns the value of the specified number as an int. This may involve rounding or truncation.

有关舍入位的详细信息会有所帮助!

A bit more info about the rounding would have been helpful!

推荐答案

Java的舍入到零,从浮点到整数类型&mdash缩小时,也是如此C#中,当您使用铸造转换。这是 Convert.ToInt32 即发:

Java rounds toward zero when narrowing from a floating point to an integer type—and so does C#, when you use the casting conversion. It's Convert.ToInt32 that rounds:

double d = 1.71472;
int x = (int) d; // x = 1
int y = Convert.ToInt32(d); // y = 2

详细信息可以在 Java语言规范。请注意,虽然文件中引用次数离开选项打开的子类,文档上的具体拳击类型,如的 双击,是明确有关实施:

Details can be found in the Java Language Specification. Note that while the documentation cited in Number leaves options open for subclasses, the documentation on the concrete boxing types, like Double, is explicit about the implementation:

返回此Double作为价值   INT(通过强制转换为int类型)。

Returns the value of this Double as an int (by casting to type int).

在使用 BigDecimal的 ,您可以指定八个不同的舍入的政策之一。

When using BigDecimal, you can specify one of eight different rounding policies.