java - 将 Double 转换为 Int 时的不同答案 - Java 与 .Net

标签 java .net rounding

在 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/

相关文章:

java - 将 cacerts 文件保存在 JRE 之外的位置有什么好处?

java - jnlp 中的 jar 资源未由同一证书签名

c# - .NET 异步 Oracle 连接的方法

c# - c#中的整数数学

objective-c - Objective-C 中的舍入数字

java - 对于大数字,从 DecimalFormat.format() 获取不正确的结果

java.lang.IllegalStateException : This consumer has already been closed

c# - 当对象具有集合属性时投影 IQueryable<object> 时 Automapper 失败

c# - 使用运行时确定的类型实例化对象

objective-c - 四舍五入 NSDecimalNumber