简体   繁体   English

如何将字符串转换为 JavaScript 中的数字?

[英]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.在我的 Oracle Apex 应用程序中,我必须对表中的值求和,但值必须是我无法存储在表编号中的字符串。

Example value in a table: <span style="color: #002699";=""> 30 000,00</span>表格中的示例值: <span style="color: #002699";=""> 30 000,00</span>

How to convert that value to number in JavaScript?如何将该值转换为 JavaScript 中的数字?

there are two parts有两部分

  1. Reading the value from the table.从表中读取值。
  2. Converting from string to int type从字符串类型转换为 int 类型

Here is an example of how you can do it:以下是如何执行此操作的示例:

HTML Code HTML 代码


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

JS Code JS代码


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

I hope it helps.我希望它有所帮助。

First step is to select the required elements.第一步是 select 所需的元素。 Considering multiple number of same span element with different value, they can be selected and converted to number as考虑到具有不同值的多个相同span元素,可以选择它们并将其转换为数字

// 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);

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, ""));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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