简体   繁体   English

在不使用DecimalFormat的情况下将两位数舍入到小数点后两位

[英]Rounding a double to two decimal places without using DecimalFormat

I wanted to know is it possible format a double to round to two decimal places with trailing zeros without using DecimalFormat , or importing anything for that matter? 我想知道是否可以在不使用DecimalFormat情况下,将双DecimalFormat格式格式化为带尾随零的双精度至四舍五入到小数点后两位,或者不为此导入任何内容? I've been trying to think of one for the past half hour and I can't figure it out. 在过去的半小时里,我一直在想一个,但我无法解决。

You can use String.format(); 您可以使用String.format();

String s = String.format("my double: %.2f", 3.54123);
System.out.println(s);

or directly printf 或直接打印

System.out.printf("my double: %.2f%n", 3.54123);

How about ? 怎么样 ?

(((int)(number * 100))/100.0F) 

Example

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

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