简体   繁体   中英

Formatting numbers with NumberFormat and BigDecimal.movePointRight()

I have to format values from a database to display this values in a frontend. The database values looks like this: 0.0009 and the output have to look like this 0,09 .

($F{Param1} == null)? "": NumberFormat.getInstance(Locale.GERMAN).format($F{Param1}.movePointRight(2)) + " %"

To getting this format I first use BigDecimal.movePointRight(2) to remove zeros from the number. This works fine and with the example above. I get the value 0.09 displayed. Because I need the german number format I replace the decimal point with NumberFormat(Locale.GERMAN) and this converts 0.09 to 0,09 . So perfect - it works. But I also get values like 0.0000 from database. With the code above 0.0000 is formatted to a single 0 . In fact 0.00 is needed. I understand that NumberFormat() produces this.

Is there a more elegant way to format a number from 0.0000 to 0,00 ? I'm looking to the DecimalFormat class, but found no valid pattern.

Something like this?

double d = 0.0009;
System.out.println(String.format(Locale.GERMANY, "%,.2f", d));

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