如何通过j2me api解析包含负数的字符串? [英] How to parse string containing negative number by j2me api?
问题描述
我有一个带数字的字符串.我必须解析此字符串并将这些数字存储在int,float等中.
I have a string which has numbers. I have to parse this string and store these numbers in int, float, etc. Accordingly
String str = "100,2.0,-100,19.99,0";
我可以在拆分后通过Integer.parseInt()
和Float.parseFloat()
进行操作.但是我不能做负数.它引发异常java.lang.NumberFormatException
.搜索网络后,我找不到该问题的任何解决方案.
I can do it by Integer.parseInt()
and Float.parseFloat()
after splitting. But I can't do it for negative number. It throws exception java.lang.NumberFormatException
. After searching web I couldn't find any solution for this problem.
那么我该如何解析字符串中的负整数并使用j2me api set存储到int中呢?
So how can I parse a negative integer from string and store into int using j2me api set?
推荐答案
与正数相比,解析负数应该没有什么特别的地方.
There should be nothing special to parsing negative numbers compared to positive number.
float f = Float.parseFloat("-1.0");
上面的代码应该可以正常工作.
The above code should work perfectly fine.
可能的代码错误之处在于,您正在尝试使用错误的小数点分隔符来解析浮点数.如果您的语言环境使用.
作为小数点分隔符,则上面的代码就可以了.但是,如果您的语言环境使用,
作为小数点分隔符,则解析将失败(使用NumberFormatException
).
What might be wrong with your code, is that you're trying to parse a float with the wrong decimal separator. If your locale has .
as decimal separator, the above code is OK. If however your locale has ,
as the decimal separator, the parsing will fail (with a NumberFormatException
).
因此,请确保正确分割原稿,并且分割后的每个部分均采用有效格式(例如,使用正确的小数点分隔符).
So make sure you're splitting the original correctly, and that each of the parts after the split are on a valid format (e.g. with the correct decimal separator).
更新:
如果您想知道如何使用特定的语言环境来解析数字,则可以查看
Update:
If you want to know how to parse a number using a specific locale, you could for instance look at this question.
这篇关于如何通过j2me api解析包含负数的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!