使用逗号将parseFloat转换变量转换为数字 [英] Make parseFloat convert variables with commas into numbers

查看:106
本文介绍了使用逗号将parseFloat转换变量转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让parseFloat将 userInput 提示符)转换成一个数字。



例如:

  var userInput = prompt(一个数字,5,000)
function parse_float(number){
return parseFloat(number)
}


$ b $ < userInput = 5,000 parse_Float(userInput)返回 5 。然而,如果用户输入一个值来改变其他东西(即:使银行存款或取消)然后我正常工作, parse.Float(userInput)需要返回 5000 ,而不是 5
如果有人能告诉我如何做到这一点,那将对我有所帮助。提前致谢。

解决方案

您的回答很接近,但不完全正确。



替换 不会更改原始字符串;它创建了一个新的。所以你需要创建一个变量来保存新的字符串,并调用 parseFloat



这里是固定的代码:

  function parseFloatIgnoreCommas(number){
var numberNoCommas = number.replace(/,/ g,'' );
return parseFloat(numberNoCommas);
}

我也将函数重命名为 parseFloatIgnoreCommas ,它更好地描述了它的功能。


I'm trying to get parseFloat to convert a userInput (prompt) into a number.

For example:

var userInput = prompt("A number","5,000") 
function parse_float(number) {
    return parseFloat(number)
}

When userInput = 5,000, parse_Float(userInput) returns 5.

However, if the user was inputting a value to change something else (ie: make a bank deposit or withdrawl) Then I to work properly, parse.Float(userInput) needs to return 5000, not 5. If anyone could tell me how to do this it would help me so much. Thanks in advance.

解决方案

Your answer is close, but not quite right.

replace doesn't change the original string; it creates a new one. So you need to create a variable to hold the new string, and call parseFloat on that.

Here's the fixed code:

function parseFloatIgnoreCommas(number) {
    var numberNoCommas = number.replace(/,/g, '');
    return parseFloat(numberNoCommas);
}

I also renamed the function to parseFloatIgnoreCommas, which better describes what it does.

这篇关于使用逗号将parseFloat转换变量转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆