【发布时间】: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