0

I have a input box that can only take values between 0 to 100 (float is allowed). Is there any function that can convert the string value in input box to decimal so that I can compare it?

I have tried parseFloat but if the string="10Hi", parseFloat will still return 10.

5 Answers5

0

you can use parseFloat function:

parseFloat('12.5')

for validation you can use regex:

var isValid = (inputStr.match(/^-?\d*(\.\d+)?$/));

if (isValid == null)
    alert('in valid');
else 
    alert('valid');
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
0

Well, how about isFinite ?

isFinite(10)      // true
isFinite('10.1'); // true
isFinite('10Hi')  // false
Mikko Viitala
  • 8,344
  • 4
  • 37
  • 62
0

You can use the below condition:

var str = "12.5", number;

if(isFinite(str) && str.indexOf(".") == -1)
     number = parseFloat(str);

Updated:

If you need to get the exact number only then you can simply use like below:

var str = "12.5", number;

if(isFinite(str))
     number = +str;

So it always returns the finite number including the floating value.

If str is '0x5f', then it return the value as 95 because it also a valid hexadecimal number check here.

Soundar
  • 2,569
  • 1
  • 16
  • 24
0
$(".decimal").each(function(){
    var v = $(this).val();

    //pattern: integer or decimal
    var valid = /^\d+$/.test(v) || /^\d+\.\d+$/.test(v);
});

https://jsfiddle.net/fwf3eumk/

Parfait
  • 1,752
  • 1
  • 11
  • 12
  • 1
    Doesn't allow `'.12'` or `'12.'`, which are valid decimal floats. Any consideration of leading or trailing whitespace? Also gratuitous use of jQuery: `var v = this.value` is hugely more efficient. ;-) – RobG Jun 17 '15 at 09:57
0

To check that input is a decimal float from 0 to 100 inclusive, a regular expression can be used to exclude strings like '0x5e' (which is a valid representation of a number between 0 and 100), then the string can be converted to a number to test the value is within the allowed bounds.

e.g.

function testValue(n) {
    var re = /^\s*\d*(\d\.?|\.?\d)\d*\s*$/;
    var num = Number(n)
    return re.test(n) && n >= 0 && n <= 100;
}

['12','12.','.12','12.2','0x5e'].forEach(function(v) {
  console.log(v + ' : ' + testValue(v));
});

12 : true
12. : true
.12 : true
12.2 : true
0x5e : false
RobG
  • 142,382
  • 31
  • 172
  • 209