【问题标题】:How to format this string in java?如何在java中格式化这个字符串?
【发布时间】:2015-06-22 14:08:01
【问题描述】:

如何在 Java 中格式化字符串?

我的字符串只包含像“1234.0”这样的数字,我想返回格式化的数字。

例如,给定字符串“1234.0”,结果应该是字符串“1234”。

【问题讨论】:

  • 您只想擦除小数位?不需要四舍五入?你试过什么?
  • String formatted = String.format(format, args...) 会帮助你
  • "Lazy Coder" 确实如此。
  • 程序员常用的一种方法是……编写代码。
  • docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html 或者只是删除逗号后的每个字符(从字符串开头到逗号的子字符串)。

标签: java string


【解决方案1】:

你也可以使用正则表达式:

String n = "1234.0";
n.replaceAll("\\.0*$", "");

【讨论】:

    【解决方案2】:
    try {
       String formatted = String.valueOf((int)Double.parseDouble("12345.0"));
    } catch (ParseException e) {
       // input is not a number
    }
    

    【讨论】:

      【解决方案3】:

      像这样使用 DecimalFormat:

      DecimalFormat myFormatter = new DecimalFormat("####");
      String output = myFormatter.format(value);
      

      你可以找到更多here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-19
        • 1970-01-01
        • 2010-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多