[英]How to substr and cast string to number in JavaScript?
在我的 Oracle Apex 应用程序中,我必须对表中的值求和,但值必须是我无法存储在表编号中的字符串。
表格中的示例值: <span style="color: #002699";=""> 30 000,00</span>
如何将该值转换为 JavaScript 中的数字?
有两部分
以下是如何执行此操作的示例:
HTML 代码
<span id="table"> 30 000,00</span>
JS代码
const number = document.getElementById('table').innerText;
const castedNumber = parseInt(number.replaceAll(" ", "").replaceAll(",", ""));
console.log(castedNumber);
我希望它有所帮助。
第一步是 select 所需的元素。 考虑到具有不同值的多个相同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);
简而言之,没有小数
let myStringNumber = "30,000");
let myNumber = parseInt(myStringNumber.replace(/,/g, ""));
或者如果你想要小数
let myNumber = parseFloat(myStringNumber.replace(/,/g, ""));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.