简体   繁体   中英

controling a float value with javascript

to control my input type and verify that its value is pretty a float in my form i deal with it in javascript like that:

function verifierNombre () {
var champ=document.getElementById("nperformed");
var str = champ.value;
if(str.value==' '){champ.focus();}
if (isNaN(str)) {
alert("Invalid Valid! the field must be a number");
champ.focus();
return false;
}
return true;

}

but it still false because it doesn't accept really floats. so when entering a value like '11,2' the alert is declenched.

I want to know how can I control float values with javascript. thanks.

I believe the problem may be that it's not considering 11,2 to be a valid float, instead expecting something like 11.2 . Give the 11.2 a try and see if it works. Should that be the problem, I'm not sure if there's some localization option that can be set, or if you need to manually swap the two before running isNaN .

Edit Ah, this webpage confirms it:

In many countries, it is common practice to use a decimal comma instead of a decimal point. Unfortunately, in JavaScript you have to use the decimal point, regardless of which country setting you have in your operating system. In JavaScript, only digits after a decimal comma will be used for calculations, which will produce incorrect results.

11,2 isn't a valid float. Javascript like (as far as I know) every programming language uses the . as decimal sign. so try 11.2 instead.

If you want to accept the , you can do it like this:

function verifierNombre() {
  var champ=document.getElementById("nperformed");
  var str = champ.value;
  if(str.value==' ') champ.focus();
  if (isNaN(str.replace(',','.')) {
    alert("Invalid Valid! the field must be a number");
    champ.focus();
    return false;
  }
  return true;
}

function localize_float(champ) {
  champ.value = champ.value.replace(",",".");
}

And in your form you add the onsubmit -attribute like this:

<form name="..." action="..." method="..." onsubmit="localize_float(document.getElementById("nperformed");)">

11,2 is not a valid float because the "decimal point" must be a point (.) and not a comma (,).

Replace the comma with a point:

var str = champ.value;
str = str.replace(",", ".");

Also,

if(str.value==' '){champ.focus();}

isn't a very good condition. Use a trim function instead and compare with "".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM