【问题标题】:Convert a number to a String with exactly 2 decimal places将数字转换为精确到小数点后 2 位的字符串
【发布时间】:2014-09-08 09:16:11
【问题描述】:

我目前正在使用静态String 方法String.format(String, Object) 来格式化代表数字的字符串。

我正在截断字符串,以便小数点后只有两位数。

if (!firstString[2].replaceAll("[^\\d.]", "").equals(""))
            secondString = String.format("%.2f", Float.valueOf(firstString[2].replaceAll("[^\\d.]", "")));

我想知道如何让格式化的字符串恰好有两位小数,即使它是一个整数或没有十位有效数字。

【问题讨论】:

  • String.format("%.2f", 3f) 已经返回"3.00"
  • 您真的在问如何将数字格式化为带小数位的字符串,因为您已经成功地将字符串转换为数字。

标签: java string


【解决方案1】:

当然你可以使用String.format,但你为什么不直接使用DecimalFormat,它专门用于将数字格式化为字符串?

    double value = 32d;
    DecimalFormat decimalFormat = new DecimalFormat("#.00");
    System.out.print(decimalFormat.format(value));

【讨论】:

    【解决方案2】:

    这是一个例子:

    String firstString ="3.22222222225456465";
    String newString= String.format("%.2f", Float.valueOf(firstString));
    System.out.println(newString);
    
    String intString =3;
    String newString= String.format("%.2f", Float.valueOf(intString ));
    System.out.println(newString);
    

    【讨论】:

      【解决方案3】:

      我知道,这并不重要......但只是我关于性能的 2 美分:

      static String formatUsingDecimalFormat(double value) {
          DecimalFormat decimalFormat = new DecimalFormat("#.00");
          return decimalFormat.format(value);
      }
      
      // http://stackoverflow.com/questions/8553672/a-faster-alternative-to-decimalformat-format
      static String formatBy_Peter_Lawrey(double d) {
          StringBuilder builder = new StringBuilder();
      
          if (d < 0) {
              builder.append('-');
              d = -d;
          }
          long scaled = (long) (d * 1e6 + 0.5);
          long factor = 100;
          int scale = 3;
          while (factor * 10 <= scaled) {
              factor *= 10;
              scale++;
          }
          while (scale > 0) {
              if (scale == 2) builder.append('.');
              long c = scaled / factor % 10;
              factor /= 10;
              builder.append((char) ('0' + c));
              scale--;
          }
      
          String newVal = builder.toString();
          DecimalFormatSymbols dfs = new DecimalFormatSymbols();
      
          char defDecSeparator = dfs.getDecimalSeparator();
      
          if ('.' != defDecSeparator) {
              return newVal.replace('.', defDecSeparator);
          }
          return newVal;
      }
      
      static String format_Naive(double value) {
      
          String val = Double.toString(value);
      
          int dotIndex = val.indexOf('.') + 1;
          int charsAfterDot = val.length() - dotIndex;
      
          if (charsAfterDot < 2) {
              val += "00";
          }
      
          // decimal point with a current locale
          DecimalFormatSymbols dfs = new DecimalFormatSymbols();
      
          char defDecSeparator = dfs.getDecimalSeparator();
      
          if ('.' != defDecSeparator) {
              return val.substring(0, dotIndex + 2).replace('.', defDecSeparator);
          }
          return val.substring(0, dotIndex + 2);
      }
      
      public static void main(String[] args) {
      
          for (int i = 1; i < 1000; i++) {
              double d = (22.4D / i)+i;
              formatUsingDecimalFormat(d);
              format_Naive(d);
              formatBy_Peter_Lawrey(d);
          }
      
          long s, e;
      
          //
          // DecimalFormat
          //
          s = System.currentTimeMillis();
          for (int i = 1; i < 100_000; i++) {
              formatUsingDecimalFormat((22.4D / i)+i);
          }
          e = System.currentTimeMillis();
      
          System.out.println((e - s) + " ms.");
      
          //
          // Naive
          //
          s = System.currentTimeMillis();
          for (int i = 1; i < 100_000; i++) {
              format_Naive((22.4D / i)+i);
          }
          e = System.currentTimeMillis();
      
          System.out.println((e - s) + " ms.");
      
          //
          // Peter_Lawrey
          //
          s = System.currentTimeMillis();
          for (int i = 1; i < 100_000; i++) {
              formatBy_Peter_Lawrey((22.4D / i)+i);
          }
          e = System.currentTimeMillis();
      
          System.out.println((e - s) + " ms.");
      
      }
      

      输出:

      422 ms.
      66 ms.
      48 ms.
      

      【讨论】:

        猜你喜欢
        • 2010-12-07
        • 1970-01-01
        • 1970-01-01
        • 2015-08-25
        • 2018-12-19
        • 2015-05-25
        • 2013-07-02
        • 2012-02-05
        • 1970-01-01
        相关资源
        最近更新 更多