Home > Software engineering >  How to transform all strings to numbers, except actual strings in Javascript?
How to transform all strings to numbers, except actual strings in Javascript?

Time:09-18

I am trying to transform all values from strings, except values that are actually strings, within the Javascript Excel Add-in API.

Example:

"1000" -> 1000
"3.2" -> 3.2
"banana" -> "banana"

CodePudding user response:

This function will help you solve the problem:

var values = ['1000','3.2','banana'];

function stringToNumber(arrayOfValues) {
  for (var i = 0; i < arrayOfValues.length; i  ) {
    if (typeof arrayOfValues[i] != 'string' || isNaN(arrayOfValues[i])) {
      continue;
    }
    arrayOfValues[i] =  arrayOfValues[i];  //   before a string converts it to number
  }
}

CodePudding user response:

You can create a helper function where you use your own rules to determine whether a string is a number or not:

function asNumberIfPossible (str) {
  if (str === '') return str;
  const n = Number(str);
  return Number.isNaN(n) ? str : n;
}

const examples = [
  '1000',
  '3.2',
  'banana',
  '0',
  '',
  '1.2e5',
  '0xfff',
  '0b101',
  ' 0',
  '0 ',
  '0 1',
  '15px',
  '28.5px',
];

for (const str of examples) {
  const result = asNumberIfPossible(str);
  console.log(
    typeof result,
    JSON.stringify(str),
    '->',
    JSON.stringify(result),
  );
}

Note that using the Number() constructor to coerce strings is more strict than using parseInt() or parseFloat(). When using parseFloat(), for example, the string "28.5px" becomes the number 28.5, but using the Number() constructor to coerce the string will result in NaN. This strictness is desirable in my opinion because it prevents a loss of information during the coercion:

const str = '28.5px';

console.log('parseFloat:', parseFloat(str));
console.log('Number:', Number(str));

CodePudding user response:

Just use the unary plus operator. Any string can be turned into a number using it, as long as the string is exclusively a number.

var x =  ”1000”; // results in 1000
var y =  ”Hi” // NaN

CodePudding user response:

You can use parseFloat() to check if the value is a number or not

if(parseFloat(value)) {
    // value is a number
  } else {
    // value is not a number
  }

  • Related