TonyS
TonyS

Reputation: 99

How to substr and cast string to number in JavaScript?

In my Oracle Apex application I have to sum values in a table but values has to be a string I can't store in a table numbers.

Example value in a table: <span style="color: #002699" ;=""> 30 000,00</span>

How to convert that value to number in JavaScript?

Upvotes: 0

Views: 197

Answers (3)

Dale
Dale

Reputation: 1628

In short, for no decimal

let myStringNumber = "30,000");
let myNumber = parseInt(myStringNumber.replace(/,/g, ""));

or if you want the decimal

let myNumber = parseFloat(myStringNumber.replace(/,/g, ""));

Upvotes: 0

P.Jaiswal
P.Jaiswal

Reputation: 1

First step is to select the required elements. Considering multiple number of same span element with different value, they can be selected and converted to number as

// The `span-selector` must be replaced with the unique selector for
// finding the required span elements
// Returns a NodeList

const tableValues = document.querySelectorAll('span-selector');
const tableValuesConvertedToNumber = tableValues.map((node) => {
   // `innerText` property will contain the number 30 or any other value
   const value = node.innerText;
   // We need to check that the value must be a valid number inside the string
   // empty string or invalid string will cause parseFloat to throw error
   // here you should perform the cleaning operation such as removing , and non numeroc characters
   if (value.length === 0) return 0;
   // you can also use parseInt if you want the output to be int
   return parseFloat(value);
});

console.log(tableValuesConvertedoNumber);

Upvotes: 0

paransaik
paransaik

Reputation: 106

there are two parts

  1. Reading the value from the table.
  2. Converting from string to int type

Here is an example of how you can do it:

HTML Code


    <span id="table"> 30 000,00</span>

JS Code


    const number = document.getElementById('table').innerText;
    const castedNumber = parseInt(number.replaceAll(" ", "").replaceAll(",", ""));
    console.log(castedNumber);

I hope it helps.

Upvotes: 1

Related Questions