简体   繁体   English

使用 DecimalFormat 将双数截断为两位小数:API 的使用记录为 @since 1.6+ 错误

[英]Truncate double numbers to two decimal places using DecimalFormat: Usage of API documented as @since 1.6+ error

I'm trying to use this code to get number 2.90 printed from the intial number 2.90689 :我正在尝试使用此代码从初始数字2.90689打印数字2.90

double number = 2.90689;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.FLOOR);  //error
System.out.println(df.format(number));

However I get the Usage of API documented as @since 1.6+ error when trying to set rounding mode.但是Usage of API documented as @since 1.6+ error在尝试设置舍入模式时,我将Usage of API documented as @since 1.6+ errorUsage of API documented as @since 1.6+ error How do I solve this in a modern way?我如何以现代方式解决这个问题? All answers I've found use this seemingly deprecated code.我找到的所有答案都使用这个看似已弃用的代码。

PS: It's not an error, but a warning in IDE. PS:这不是错误,而是IDE中的警告。 When run, it also doesn't work properly: prints 2.9 instead of 2.90 .运行时,它也无法正常工作:打印2.9而不是2.90 I've made this repl: https://repl.it/repls/IllInterestingComputers .我做了这个 repl: https : //repl.it/repls/IllInterestingComputers

Screenshot of the warning:警告截图: 在此处输入图片说明

double number = 2.90689;
DecimalFormat df = new DecimalFormat("#.00");
df.setRoundingMode(RoundingMode.FLOOR);  //error
System.out.println(df.format(number));

Please check https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html请检查https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent

You should use BigDecimal , heres an example: 您应该使用 BigDecimal ,这是一个示例:

double number = 2.90689;
BigDecimal roundedDown = BigDecimal.valueOf(number).setScale(2, RoundingMode.DOWN);
System.out.println("Original: " + number);
System.out.println("Rounded: " + roundedDown);

Stdout:标准输出:

Original: 2.90689
Rounded: 2.90

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM