英文:
Java number format validation
问题
我需要验证Java中验证数字格式的解决方案。作为输入参数,我接收一个字符串。例如,欧洲格式为:1.234,56。然后我进行解析:
NumberFormat.getNumberInstance(locale).parse(value)
但在解析之前,我需要进行验证。输入数据的示例:
1..234,,56 - 不应该有效,但它是可解析的。
英文:
Can you please advice solution in Java to validate number formats.
As input param I receive String. For example, there is Europe format: 1.234,56
Then I do parsing:
NumberFormat.getNumberInstance(locale).parse(value)
But before parsing I need validation.
Example of input data:
1..234,,56 - shouldn't be valid but it parsable
答案1
得分: 1
你可以开始构建正则表达式来检查字符串中是否包含逗号或小数点的格式。还可以参考以下正则表达式:
^\d{1,3}|\d(([ ,]?\d{3})*([.,]\d{2}+)?$)
你还可以查看这个链接:https://stackoverflow.com/questions/42822629/java-regex-to-check-if-string-is-valid-number-format-comma-and-decimal-point-pl
英文:
You can go with building your regular expression to check for the format having commas or decimals in a string.
Also take reference from the regular expression like :
^\d{1,3}|\d(([ ,]?\d{3})*([.,]\d{2}+)?$)
You can also have a look to this one: https://stackoverflow.com/questions/42822629/java-regex-to-check-if-string-is-valid-number-format-comma-and-decimal-point-pl
答案2
得分: 0
好的,以下是翻译好的部分:
有许多可能的解决方案。但对于这种情况,最好使用异常。当无法将字符串转换为数字时,基本上向用户输出一条消息,告诉他输入了错误的数字,并要求他输入新的数字。为了选择正确的数字类型,您可以使用重载
。
try {
NumberFormat.getNumberInstance(locale).parse(value)
}
catch(Exception e) {
System.out.println("输入的数字无效。");
// 输入新数字的代码
}
英文:
Well, there are many possible solutions. But for this situation it would be good to use exceptions. When it is not possible to convert the string into a number, basically write a message to the user that he wrote the wrong number and ask him to enter the new one. For selecting the correct number type, you can use overloading
.
try {
NumberFormat.getNumberInstance(locale).parse(value)
}
catch(Exception e) {
System.out.println("The number entered is invalid.");
// Enter the new number code
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论