Java保留两位小数的几种做法

时间:2023-03-08 19:15:22
Java保留两位小数的几种做法

1. 

String类型数字始终保留两位小数

public static void main(String[] args) {    
    DecimalFormat format = new DecimalFormat("0.00");
    String abc ="100.456";
    String a = format.format(new BigDecimal(abc));
    System.out.println(a);
    }

2. 另外几种办法

原文

在平时做项目时,可能有这样的业务需求:页面或界面上展示的数据保留小数点后两位。

为了达到这样的展示效果,本文列举了几个方法:

1. 使用java.math.BigDecimal 
2. 使用java.text.DecimalFormat 
3. 使用java.text.NumberFormat 
4. 使用java.util.Formatter 
5. 使用String.format

... ... 另外可以自己实现或者借用封装好的类库来实现,在这篇文章中就不一一列举了。

本文给出上述5种方法的简单实现。

代码如下: 

  1. import java.math.BigDecimal;
  2. import java.math.RoundingMode;
  3. import java.text.DecimalFormat;
  4. import java.text.NumberFormat;
  5. import java.util.Formatter;
  6. public final class PrecisionTest {
  7. private PrecisionTest() {
  8. }
  9. /**
  10. * 使用BigDecimal,保留小数点后两位
  11. */
  12. public static String format1(double value) {
  13. BigDecimal bd = new BigDecimal(value);
  14. bd = bd.setScale(2, RoundingMode.HALF_UP);
  15. return bd.toString();
  16. }
  17. /**
  18. * 使用DecimalFormat,保留小数点后两位
  19. */
  20. public static String format2(double value) {
  21. DecimalFormat df = new DecimalFormat("0.00");
  22. df.setRoundingMode(RoundingMode.HALF_UP);
  23. return df.format(value);
  24. }
  25. /**
  26. * 使用NumberFormat,保留小数点后两位
  27. */
  28. public static String format3(double value) {
  29. NumberFormat nf = NumberFormat.getNumberInstance();
  30. nf.setMaximumFractionDigits(2);
  31. /*
  32. * setMinimumFractionDigits设置成2
  33. *
  34. * 如果不这么做,那么当value的值是100.00的时候返回100
  35. *
  36. * 而不是100.00
  37. */
  38. nf.setMinimumFractionDigits(2);
  39. nf.setRoundingMode(RoundingMode.HALF_UP);
  40. /*
  41. * 如果想输出的格式用逗号隔开,可以设置成true
  42. */
  43. nf.setGroupingUsed(false);
  44. return nf.format(value);
  45. }
  46. /**
  47. * 使用java.util.Formatter,保留小数点后两位
  48. */
  49. public static String format4(double value) {
  50. /*
  51. * %.2f % 表示 小数点前任意位数 2 表示两位小数 格式后的结果为 f 表示浮点型
  52. */
  53. return new Formatter().format("%.2f", value).toString();
  54. }
  55. /**
  56. * 使用String.format来实现。
  57. *
  58. * 这个方法其实和format4是一样的
  59. */
  60. public static String format5(double value) {
  61. return String.format("%.2f", value).toString();
  62. }
  63. }

测试代码及结果:

Java代码  Java保留两位小数的几种做法
  1. public class Main {
  2. public static void main(String[] args) {
  3. double[] testData = new double[] { .123D, .897D, .0052D,
  4. .00D };
  5. for (double value : testData) {
  6. System.out.println(PrecisionTest.format1(value));
  7. System.out.println(PrecisionTest.format2(value));
  8. System.out.println(PrecisionTest.format3(value));
  9. System.out.println(PrecisionTest.format4(value));
  10. System.out.println(PrecisionTest.format5(value));
  11. }
  12. }
  13. }

100.12 
100.12 
100.12 
100.12 
100.12 
1234567.90 
1234567.90 
1234567.90 
1234567.90 
1234567.90 
100.01 
100.01 
100.01 
100.01 
100.01 
80.00 
80.00 
80.00 
80.00 
80.00