最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - check if a given value is a positive number or float with maximum two decimal places - Stack Overflow

programmeradmin3浏览0评论

I am trying to implement a validation check for an input text control which should allow only a positive integer value or a float with maximum 2 decimal places.

Here is the fiddler with the approaches I've tried: /

HTML

Enter Price: <input type="text" id="price"/> (Example: 10, 10.50. Do not include $ symbol.)
<br/>
<br/>
<button type="button" id="check1">Check Method 1</button> (Fails when the value is 1.00)
<br/>
<br/>
<button type="button" id="check2">Check Method 2</button> (Passes when the value is 45f)
<br/>
<br/>
<button type="button" id="check3">Check Method 3</button> (Passes when the value is -10)

Code:

var price = $('#price');

$('#check1').on('click', function(){
   var val = $.trim(price.val());
    var num = Number(val);
    if (String(num) === val && num >= 0)
    {
        alert('Valid');
    }
    else
    {
        alert('Invalid');
    }
});

$('#check2').on('click', function(){
   var val = $.trim(price.val()); 
   var num = Number(val);

    if (((typeof num === 'number') && (num % 1 === 0)) || parseFloat(val))
    {
        alert('Valid');
    }
    else
    {
        alert('Invalid');
    }
});

$('#check3').on('click', function(){
   var val = $.trim(price.val());  

    if ($.isNumeric(val))
    {
        alert('Valid');
    }
    else
    {
        alert('Invalid');
    }
});

Expectation:

The values that should be passed are positive numbers and float with maximum 2 decimals. (example 10, 10.50)

I looked at various answers in stackoverflow but non matched with my expectation. Any help is appreciated.

I am trying to implement a validation check for an input text control which should allow only a positive integer value or a float with maximum 2 decimal places.

Here is the fiddler with the approaches I've tried: https://jsfiddle/99x50s2s/49/

HTML

Enter Price: <input type="text" id="price"/> (Example: 10, 10.50. Do not include $ symbol.)
<br/>
<br/>
<button type="button" id="check1">Check Method 1</button> (Fails when the value is 1.00)
<br/>
<br/>
<button type="button" id="check2">Check Method 2</button> (Passes when the value is 45f)
<br/>
<br/>
<button type="button" id="check3">Check Method 3</button> (Passes when the value is -10)

Code:

var price = $('#price');

$('#check1').on('click', function(){
   var val = $.trim(price.val());
    var num = Number(val);
    if (String(num) === val && num >= 0)
    {
        alert('Valid');
    }
    else
    {
        alert('Invalid');
    }
});

$('#check2').on('click', function(){
   var val = $.trim(price.val()); 
   var num = Number(val);

    if (((typeof num === 'number') && (num % 1 === 0)) || parseFloat(val))
    {
        alert('Valid');
    }
    else
    {
        alert('Invalid');
    }
});

$('#check3').on('click', function(){
   var val = $.trim(price.val());  

    if ($.isNumeric(val))
    {
        alert('Valid');
    }
    else
    {
        alert('Invalid');
    }
});

Expectation:

The values that should be passed are positive numbers and float with maximum 2 decimals. (example 10, 10.50)

I looked at various answers in stackoverflow but non matched with my expectation. Any help is appreciated.

Share Improve this question asked Jun 2, 2015 at 20:50 JGVJGV 5,1979 gold badges56 silver badges101 bronze badges 4
  • 1 I was going to vote up on @talemyn's answer below but one thing you should clarify for everyone is what you expect it to happen when someone supplies it with a value that could be rounded up. For example, if someone puts in 10.509 - do you want to accept that as 10.51 or do you say that it's invalid. – jgo Commented Jun 2, 2015 at 21:09
  • That's a good question @jgo . . . my assumption was that the value would be invalid, because it had 3 decimal points. "Autocorrecting" it to a rounded value would definitely change the approach. – talemyn Commented Jun 2, 2015 at 21:13
  • @jgo, in my application, when someone key in 10.509, I would like to show it as invalid. – JGV Commented Jun 2, 2015 at 21:21
  • Thanks for clarifying. I just voted up on @talemyn 's answer. I think the toFixed version presented by Erik below would've been viable but at the end of the day, that's still a "string" (i.e. pattern-based) based validate - not to mention the fact that it's actually paring a String to a Number since toFixed() returns a string the num variable is a Number. – jgo Commented Jun 2, 2015 at 21:36
Add a ment  | 

2 Answers 2

Reset to default 8

What you are really looking for is that the value matches a pattern, not what it's value is. For that, you are probably best off using a regular expression. Specifically, this should catch the value that you are looking for:

/^\d+(\.\d{1,2})?$/

That says:

  • starting at the beginning of the value (^)
  • match 1 or more digits (\d+)
  • followed by an option decimal point and 1 or two digits ((\.\d{1,2})?)
  • and no other characters before the end of the value ($)

That should enforce all of your rules, allowing you to perform a single check for validity, rather than multiple ones.


Edit: Here is an example of how to use it:

function checkNumber(sNum) {
    var pattern = /^\d+(\.\d{1,2})?$/;
    console.log(sNum + " is " + ((pattern.test(sNum)) ? "" : "not ") + "valid.");
}

checkNumber("1");      // 1 is valid.
checkNumber("-1");     // -1 is not valid.
checkNumber("1234");   // 1234 is valid.
checkNumber("1.");     // 1. is not valid.
checkNumber("1.0");    // 1.0 is valid.
checkNumber("1.12");   // 1.12 is valid.
checkNumber("1.123");  // 1.123 is not valid.

I would imagine it would be:

var num = Number(val);

if (!isNaN(num)
    && num > 0
    && num == num.toFixed(2))
{
  // Valid
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论