在 C# 中,如果我想将 double (1.71472) 转换为 int,那么我会得到答案 2。如果我在 Java 中使用 intValue() 方法执行此操作,我会得到 1 作为答案。
Java 是否会降低转换次数?
为什么 Java API 文档对它们的类的信息如此匮乏,即
Returns the value of the specified number as an int. This may involve rounding or truncation.
有关舍入的更多信息会有所帮助!
最佳答案
当从 float 缩小到整数类型时,Java 会向零舍入——当您使用强制转换时,C# 也是如此。舍入的是 Convert.ToInt32
:
double d = 1.71472;
int x = (int) d; // x = 1
int y = Convert.ToInt32(d); // y = 2
详细信息可以在 Java Language Specification 中找到.请注意,虽然 Number
中引用的文档为子类保留了选项,但有关具体装箱类型的文档,如 Double
,明确说明了实现:
Returns the value of this Double as an int (by casting to type int).
使用 BigDecimal
时, 您可以指定八种不同的舍入策略之一。
关于java - 将 Double 转换为 Int 时的不同答案 - Java 与 .Net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/300055/