【问题标题】:Difficulty parsing a double - String解析双精度字符串的困难
【发布时间】:2012-05-21 02:00:46
【问题描述】:

感谢您花时间回答我的问题。

我有一个 double 值(比如说 22.35)。我需要将其解析为String 并得到2235。以下代码无法正常工作。

double totalPrice = 22.35;
DecimalFormat df = new DecimalFormat("#.##");
String[] temp = df.format(totalPrice).split(".");
String amount = temp[0] + temp[1];

我不断收到异常ArrayIndexOutOfBounds。还有什么方法可以做到这一点?提前致谢!

【问题讨论】:

  • int totalCents = (int)(22.35d*100);
  • @AndrewThompson - 对我来说似乎是一个答案,也许有一两句话可以解释。 +1
  • 你为什么不把点字符替换为一个空字符?
  • @jmort253 很棒的评论! :) 让我们希望它“听起来更好”(如 - 不会被删除)你所说的方式。

标签: java string parsing double


【解决方案1】:

如果你的值不超过,乘以 100 后,MAX_INT,将它们相乘:

double totalPrice = 22.35;
int iPrice = (int) (totalPrice * 100);
String sPrice = "" + iPrice;

【讨论】:

  • @AndrewThompson:抱歉,忘记投了。
  • @userunknown - 恭喜获得 10k!
  • @jmort253:谢谢。最后的 2000 年发生在他们自己身上。
【解决方案2】:

怎么样:

double totalPrice = 22.35;
DecimalFormat df = new DecimalFormat("#.##");
String price = df.format(totalPrice).replace(".", "");

【讨论】:

    【解决方案3】:

    也许您可以这样做:只需更改正则表达式“。”到“\.”!

    String[] temp = df.format(totalPrice).split("\\.");
    

    【讨论】:

      【解决方案4】:

      无论您尝试将其应用于多高的数字,这都会起作用:

      double num = 22.35;
      String concatenate = "" + num;
      String parsedNum = concatenate.replace(".", "");
      

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-21
        • 2010-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多