0

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?

TonyS
  • 89
  • 11
  • https://stackoverflow.com/questions/1133770/how-to-convert-a-string-to-an-integer-in-javascript – Jash1395 Jan 12 '23 at 11:30
  • Are you asking how to convert a string to a number in JS ? You can use `Number("...")` or `parseInt("...")` or `parseFloat("...")` etc, regarding what you need – Peterrabbit Jan 12 '23 at 11:32
  • No, I am asking how to substr string and then cast it to number, I can't convert string I paste to number – TonyS Jan 12 '23 at 11:35
  • So you want to convert 30,000 to a number? Is that right? – Dale Jan 12 '23 at 11:41

3 Answers3

1

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.

paransaik
  • 96
  • 1
  • 6
0

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);
P.Jaiswal
  • 1
  • 1
0

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, ""));
Dale
  • 1,613
  • 4
  • 22
  • 42