简体   繁体   中英

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? 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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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