如果不为零,则格式化float以显示小数位Java [英] Format float to show decimal places if is not zero java
本文介绍了如果不为零,则格式化float以显示小数位Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
仅当浮点数与零不同时,才需要显示浮点数.
I need to to show decimal places of a float value only when it is different from zeros.
- 5.0 应该显示为 5 .
- 7.3 应该显示为 7.3 .
- 9.000003 应该显示为 9.000003 .
- 5.0 should be shown as 5.
- 7.3 should be shown as 7.3.
- 9.000003 should be shown as 9.000003.
如何使用正则表达式或DecimalFormat以这种方式进行格式化?
How to format in this way using regex or DecimalFormat?
推荐答案
要以所需的方式显示小数,请使用以下代码段:
To display decimals the way you desire, use the following snippet:
// This is to show symbol . instead of ,
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
// Define the maximum number of decimals (number of symbols #)
DecimalFormat df = new DecimalFormat("#.##########", otherSymbols);
// type: double
System.out.println(df.format(5.0)); // writes 5
System.out.println(df.format(7.3)); // writes 7.3
System.out.println(df.format(9.000003)); // writes 9.000003
// type: float
System.out.println(df.format(9.000003f)); // writes 9.000002861
这篇关于如果不为零,则格式化float以显示小数位Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文