验证输入字符串是有效的十进制数 [英] verify input string is valid decimal number

查看:100
本文介绍了验证输入字符串是有效的十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以提供检查输入的字符串是否在正确的形状一个十进制数,并形成一种算法

Can anybody provide an algorithm that checks whether an input string is a decimal number in correct shape and form?

正确的形状和形式的规则:

Rules of correct shape and form:


  1. 在最小数点后两位。

  2. 对于所有的实际目的,人数最多的为99,999,999.99

  3. 的组成部分可以用空格或逗号,或者一个点为一组分隔符。

  4. 的小数部分可以用逗号或一个点的。分离

  5. 正确的形状和形式
  1. At most two decimal places.
  2. For all practical purposes, the largest number is 99,999,999.99
  3. The integral part can use a space, or a comma, or a dot for a group separator.
  4. The decimal part can use a comma, or a dot for a separator.

例如:


1,234,567.89   // English style
1.234.567,89   // French style
1 234 567,89   // German style
1234567.89     // English mathematical style
1234567,89     // European mathematical style
12.00
12.0
12

请,抗拒你的诱惑建议Decimal.Parse或Decimal.TryParse。两种方法都欢快地接受字符串,如1,2,3,4,这是不是我想要的。

Please, resist your temptation to propose Decimal.Parse or Decimal.TryParse. Either method merrily accepts strings such as "1,2,3,4", which is not what I want.

推荐答案

< A HREF =htt​​p://stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text/5917250#5917250>我回答了上周五非常类似的问题,和正则表达式来做到这一点会比你想象的更复杂。我强烈建议每个风格设置单独的正则表达式 - 不是因为它不能在一行中完成的,但由于一个班轮这将是大,非常艰难维持

I answered a very similar question on Friday, and the regex to do this is going to be more complicated than you think. I strongly suggest setting up a separate regex for each style - not because it can't be done in one line, but because a one-liner for this is going to be big and pretty tough to maintain.

下面是我会使用模式:

English: ^[-+]?\d{1,3}(,\d{3})*(\.\d+)?$
French: ^[-+]?\d{1,3}(\.\d{3})*(,\d+)?$
German: ^[-+]?\d{1,3}(\s\d{3})*(,\d+)?$
English mathematical: ^[-+]?\d+(\.\d+)?$
European mathematical: ^[-+]?\d+(,\d+)?$

这些可以组合成类似:

^[-+]?(\d{1,3}((,\d{3})*(\.\d+)?|([.\s]\d{3})*(,\d+)?)|\d+([,\.]\d+)?)$

希望这一个班轮适当可怕的给你。这是一个很常见的,重要的任务,但它也是一个比它出现更复杂的

Hopefully that one-liner is appropriately terrifying to you. This is a very common, important task, but it's also one that's more complicated than it appears.

在Rubular你的榜样输入测试:的 http://rubular.com/r/Dipvyrf6C8 (请注意,我做了组非捕获的结果清晰)。

Tested at Rubular with your example inputs: http://rubular.com/r/Dipvyrf6C8 (note that I made the groups non-capturing for clarity of the results).

编辑:新增 [ - +] 子句允许负数

这篇关于验证输入字符串是有效的十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆