简体   繁体   English

如何使用parseInt而不是parseFloat转换代表小数的字符串?

[英]How to convert string representing a decimal using parseInt instead of parseFloat?

Given a string that represents a number use parseInt to convert string to number. 给定表示数字的字符串,请使用parseInt将字符串转换为数字。 I wrote a working function, but did not account for decimal numbers. 我编写了一个工作函数,但没有考虑十进制数字。 Is there a way to convert decimals using parseInt? 有没有一种方法可以使用parseInt转换小数? This is as far as I've gotten trying to account for decimals. 据我所知,这只是尝试计算小数。 The problem with this is NaN being returned. 问题是NaN被返回。 I can't think of a solution to implement that filters NaN from the results. 我想不出实现从结果中过滤NaN的解决方案。 The ultimate goal is to compare the two strings. 最终目标是比较两个字符串。 My solution must use parseInt. 我的解决方案必须使用parseInt。

function convertStr(str1, str2) {
let num1 = str1.split('')
let num2 = str2.split('');
num1 = num1.map(str => parseInt(str));
num2 = num2.map(str => parseInt(str));
console.log(num1);
console.log(num2);
}

Any help is greatly appreciated. 任何帮助是极大的赞赏。

I think this is a good step to what you are seeking for : 我认为这是您要追求的目标的好一步:

The question is : What do you want as output when encountering decimal value? 问题是 :遇到十进制值时要输出什么?

 // Soluce to replace NaN by '.' function convertStrReplace(str1) { let num1 = str1.split('') num1 = num1.map(str => parseInt(str)).map(x => isNaN(x) ? '.' : x); console.log(num1); } // Soluce to ignore NaN function convertStrIgnore(str1) { let num1 = str1.split('') num1 = num1.map(str => parseInt(str)).filter(x => !isNaN(x)); console.log(num1); } convertStrReplace('17,52'); convertStrIgnore('17,52'); 


Syntax alternative 语法替代

 function convertStrFilter(str1) { const num1 = [ ...str1, ].map(str => parseInt(str)).filter(x => !isNaN(x)); console.log(num1); } convertStrFilter('17,52'); 


Explaination about integer and string differences 关于整数和字符串差异的解释

 // String and integer differences // Put a number into a string const str = '9000'; console.log(typeof str, str); // Put a number into a number const number = 9000; console.log(typeof number, number); // Compare both (compare value and type) console.log('equality ===', str === number); // Compare both (compare value) console.log('equality ==', str == number); const numberFromString = parseInt(str); console.log(typeof numberFromString, numberFromString); // Compare both (compare value and type) console.log('equality ===', number === numberFromString); 

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

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