使用println和printf进行不同的舍入 [英] Different rounding with println and printf

查看:108
本文介绍了使用println和printf进行不同的舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于精度损失,下面的第一行将打印0.8999999999999999,这很清楚.但是第二行将显示0.9,我只是不明白为什么.这种计算不应该有同样的问题吗?

The first line below will print 0.8999999999999999 because of precision loss, this is clear. But the second line will print 0.9, I just do not understand why. Shouldn't there be the same problem with this calculation?

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

推荐答案

我认为您在使用System.out.printf()时缺少一些东西,如果您未显式设置宽度,则C中printf的默认行为(即如果未明确指定,则保留小数点后6位)

I think you are missing something as using System.out.printf(), if you do not explicit formatting widths then default behavior of printf in C (which is 6 decimal places if not explicitly specified)

因此,如果您不会为%f指定任何数字,则默认情况下它将仅打印1个字符.但是,如果要更改小数点后的数字,则需要将其指定为%.2f,这样会将数字打印到小数点后2位.

So if you will not specify any number to %f then by default it will print only 1 character. However if you want to change the number after the decimal then you need to specify it like %.2f, this will print the number to 2 decimal places.

所以它类似于

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

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

float格式说明符的常规语法为:

As the general syntax for format specifier for float is:

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

附带说明:-

还有一个格式化程序类.

用于printf样式格式字符串的解释器.该课程提供 支持布局调整和对齐,通用格式 数字,字符串和日期/时间数据,以及特定于语言环境的输出. 常见的Java类型(例如byte,BigDecimal和Calendar)是 支持的.针对任意用户类型的有限格式定制 是通过Formattable接口提供的.

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

如果未指定精度,则默认值为6. 精度小于之后将出现的位数 Float.toString(float)返回的字符串中的小数点或 Double.toString(double)分别,则该值将被四舍五入 使用上舍入算法.

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.

这篇关于使用println和printf进行不同的舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆