search

Home  >  Q&A  >  body text

javascript - Regular validation of numbers or decimals, definitely a challenge

1. Only regular expressions can be used to verify
2. When the number is a decimal, it needs to be verified with two decimal places
3. It cannot be 0, 0.00
4. It can be 0.10, 0.11, 1, Number type like 0.01

大家讲道理大家讲道理2770 days ago707

reply all(6)I'll reply

  • 滿天的星座

    滿天的星座2017-05-19 10:18:45

    Is this an interview question? You can solve it with Math.round

    reply
    0
  • PHPz

    PHPz2017-05-19 10:18:45

    Give you a reference/q/10...

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:18:45

    ^[-+]?\d+(\.\d{0,1}[1-9])?$

    Update
    ^[-+]?([1-9]+)|(\d+\.(\d{0,1}[1-9])|(\[1-9][0-9]))$

    ^(([1-9]+)|(\d+\.((\d{0,1}[1-9])|([1-9][0-9]))))$

    0 - false
    0.01 - true
    0.00 - false
    0.10 - falsetrue

    Update #2

    Starts with a number except 0.

    ^((^[1-9][0-9]*)|((^[1-9][0-9]*)\.((\d{0,1}[1-9])|([1-9][0-9]))))$

    02.01 - false
    2.01 - true
    2.00 - false
    2.10 - true

    reply
    0
  • 为情所困

    为情所困2017-05-19 10:18:45

    /^([0-9]+.[0-9]{0,2}|[1-9])*$/

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-19 10:18:45

    /^[+-]?\d+(\.\d{2})?$/

    or

    /^[+-]?\d+(?:\.\d{2})?$/

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:18:45

    var arr = [0, 0.00, 0.10, 0.11, 1, 0.01, -0, -0.00, -0.10, +0.11, -1, -0.01];
    var reg = /^[+-]?([1-9]{1}\d?|[1-9]+.\d{2}|0.[1-9]{1}\d{1}|0.0[1-9]{1})$/;
    for (let i = 0, len = arr.length; i < len; i++) {
        console.log(arr[i], reg.test(arr[i]));
    }

    reply
    0
  • Cancelreply