Verify decimals [closed]

-1

function c(n) {
  var v;
  if (n % 1 !== 0) v = parseFloat(n); // Verifico si el numero es decimal y uso parseFloat
  else v = parseInt(n); // Verifico si el numero es entero y uso parseInt

  return v; // Retorno el numero
}

console.log(c("45.2")); // Llamo a la función

Assuming that JavaScript did not transform the string into numbers, how could you verify that n%1 , if it were first would be a string ?

    
asked by Eduardo Sebastian 30.08.2017 в 18:49
source

2 answers

2

So you can validate if it's a string

function esString(myVar){
  return (typeof myVar == 'string' || myVar instanceof String);
}

console.log(esString(1));
console.log(esString("1"));
console.log(esString(new String(1)));

And it is always advisable to parse string to numbers

function esString(myVar){
      return (typeof myVar == 'string' || myVar instanceof String);
    }
    
function suma(var1, var2){
  
  var numVar1 = var1;
  
  var numVar2 = var2;

  if(esString(var1)){
      if(var1.indexOf(".")>=0)
        numVar1 = parseFloat(var1);
      else
        numVar1 = pareseInt(var1, 10);
  }

  if(esString(var2)){
      if(var2.indexOf(".")>=0)
        numVar2 = parseFloat(var2);
      else
        numVar2 = pareseInt(var2, 10);
  }
  console.log( numVar1 + numVar2 );
}

suma("5.2", 12);
    
answered by 30.08.2017 в 18:57
0

What I can understand about your question is that javascript does the conversion on its own and you want to know how it would be verified if a string is decimal if javascript did not do the conversion automatically. Well in this case just looking if you have a point with indexOf() , since decimals will always be accompanied by a period:

function c(n) {
  var v;
  if (n.indexOf(".") > -1){
     console.log("decimal")
   v = parseFloat(n); 
  }else {
  console.log("int")
    v = parseInt(n); 
  }

  return v; // Retorno el numero
}

console.log(c("454.42")); 
 console.log(c("42")); 

Or with regular expressions looking for a point in the middle of numbers:

    function c(n) {
      var v;
      if (/\d+\.\d+/g.test(n)){
         console.log("decimal")
       v = parseFloat(n); 
      }else {
      console.log("int")
        v = parseInt(n); 
      }

      return v; // Retorno el numero
    }

    console.log(c("454.42")); 
 console.log(c("42")); 
 
    
answered by 30.08.2017 в 20:03