【问题标题】:Split String to String[] by a period but returning an empty array按句点将字符串拆分为字符串 [] 但返回一个空数组
【发布时间】:2012-05-12 14:06:37
【问题描述】:

好吧,也许我只需要再看一眼。

我有一个浮点数,我把它变成了一个字符串。然后,我想将其按句点/小数拆分,以便将其显示为货币。

这是我的代码:

float price = new Float("3.76545");
String itemsPrice = "" + price;
if (itemsPrice.contains(".")){
    String[] breakByDecimal = itemsPrice.split(".");
    System.out.println(itemsPrice + "||" + breakByDecimal.length);
    if (breakByDecimal[1].length() > 2){
        itemsPrice = breakByDecimal[0] + "." + breakByDecimal[1].substring(0, 2);
    } else if (breakByDecimal[1].length() == 1){
        itemsPrice = breakByDecimal[0] + "." + breakByDecimal[1] + "0";                         
    }                           
}

如果你接受它并运行它,你将在第 6 行(在上面的代码中)得到一个数组索引越界错误,关于小数点后没有任何内容。

实际上在第 5 行,当我打印出数组的大小时,它是 0。

这些错误太荒谬了,因为它们不是我忽略的东西。

就像我说的,另一双眼睛正是我需要的,所以当你指出对你来说很明显但我忽略了的事情时,请不要无礼。

提前致谢!

【问题讨论】:

    标签: java arrays string split floating-point


    【解决方案1】:

    split 使用正则表达式,其中“.”表示匹配任何字符。你需要做的

    "\\."
    

    编辑:已修复,感谢评论和编辑

    【讨论】:

    • 或者使用 Matcher.quoteReplacement()
    • 不,两个反斜杠是正确的,否则你会在字面上匹配一个反斜杠,然后是一个点 \.
    • 是的,你是对的……我的错。它自动纠正了我的错误:) 固定
    • 你也可以在句点前加一个space字符,比如:" .",这个space在拆分时不会被考虑。
    • 这个空间就像一个魅力,但由于某种原因斜线没有
    【解决方案2】:

    改用十进制格式:

    DecimalFormat formater = new DecimalFormat("#.##");
    System.out.println(formater.format(new Float("3.76545")));
    

    【讨论】:

    • 在处理金钱时,您应该使用 NumberFormat.getCurrencyInstance() 实例化的 NumberFormat。
    【解决方案3】:

    我在 java 上工作不多,但在第 2 行,可能价格没有转换为字符串。 我在 C# 中工作,我会将其用作: String itemsPrice = "" + price.ToString();

    也许您应该首先明确地将价格转换为字符串。 因为,它没有被转换,字符串只包含“”,没有“。”,所以没有拆分和扩展 arrayOutOfBounds 错误。

    【讨论】:

      【解决方案4】:

      如果您想将其显示为价格,请使用 NumberFormat。

      Float price = 3.76545;
      Currency currency = Currency.getInstance(YOUR_CURRENCY_STRING);
      NumberFormat numFormat = NumberFormat.getCurrencyInstance();
      numFormat.setCurrency(currency)
      numFormat.setMaximumFractionDigits(currency.getDefaultFractionDigits());
      String priceFormatted = numFormat.format(price);
      System.out.println("The price is: " + priceFormatted);
      

      YOUR_CURRENCY_STRING 是您正在处理的货币的 ISO 4217 货币代码。

      此外,以非精确格式(例如浮点数)表示价格通常不是一个好主意。您应该使用 BigDecimal 或 Decimal。

      【讨论】:

        【解决方案5】:

        如果您想自己处理,请尝试以下代码:

        public static float truncate(float n, int decimalDigits) {
            float multiplier = (float)Math.pow(10.0,decimalDigits);
            int intp = (int)(n*multiplier);
            return (float)(intp/multiplier);
        }
        

        然后像这样得到 truncatedPrice:

        float truncatedPrice = truncate(3.3654f,2);
        System.out.println("Truncated to 2 digits : " + truncatedPrice);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-13
          • 1970-01-01
          • 2018-08-15
          • 1970-01-01
          • 2012-02-22
          相关资源
          最近更新 更多