加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 与println和printf不同的舍入

发布时间:2020-12-15 00:25:10 所属栏目:Java 来源:网络整理
导读:下面的第一行将打印0.8999999999999999因为精度损失,这是很清楚的.但是第二行会打印0.9,我只是不明白为什么.这个计算不应该有同样的问题吗? System.out.println(2.00-1.10);System.out.printf("%f",2.00-1.10); 解决方法 我想你缺少使用System.out.printf()
下面的第一行将打印0.8999999999999999因为精度损失,这是很清楚的.但是第二行会打印0.9,我只是不明白为什么.这个计算不应该有同样的问题吗?
System.out.println(2.00-1.10);
System.out.printf("%f",2.00-1.10);

解决方法

我想你缺少使用System.out.printf()的东西,如果你没有明确的格式化宽度,那么C中的printf的默认行为(如果没有明确指定,则是6位小数位)

所以如果你不指定任何数字到%f,默认情况下它只打印1个字符.但是,如果要更改小数后的数字,则需要将其指定为%.2f,这将打印数字为2位小数.

所以它类似于写作

System.out.printf("%f",2.00-1.10);

要么

System.out.printf("%.1f",2.00-1.10);

由于float的格式说明符的一般语法是:

%[flags][width][.precision][argsize]typechar

在旁注:

Java中也有一个formatter class.

An interpreter for printf-style format strings. This class provides
support for layout justification and alignment,common formats for
numeric,string,and date/time data,and locale-specific output.
Common Java types such as byte,BigDecimal,and Calendar are
supported. Limited formatting customization for arbitrary user types
is provided through the Formattable interface.

从Oracle Docs

If the precision is not specified then the default value is 6. If the precision is less than the number of digits which would appear after the decimal point in the string returned by Float.toString(float) or Double.toString(double) respectively,then the value will be rounded using the round half up algorithm.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读