【问题标题】:Retrieving a value from a Label is NaN after parsing to a float解析为浮点数后,从标签中检索值是 NaN
【发布时间】:2016-05-31 09:09:05
【问题描述】:

我需要将销售价格从欧元转换为英镑,因此我试图将销售价格除以汇率,但它一直显示为 NaN!

var xRate = $('#MainContent_lblCurrency').text();  //The value is "1.12350" when alerted out
//xRate = "1.23345";

alert("EXC Rate is " + xRate);  //this is fine
totalEurPrice = totalEurPrice.toFixed(numDecPoints);
alert("totalEurPrice is " + totalEurPrice);  //this is fine
//now we divide to get GBP sales value
var totalPrice = parseFloat(totalEurPrice) / parseFloat(xRate);  //this gives NaN

如果我取消注释该行,xRate = "1.23345";一切正常。请有人告诉我为什么当我从标签中检索值时它不起作用(大概是作为字符串返回的)??

【问题讨论】:

  • 显然MainContent_lblCurrency 元素的文本值不可解析为数字。警报通常不会添加双引号,所以问题可能是该值周围有实际的引号字符?试试alert('"' + xRate + '"')。或者改用console.log,这是更好的做法。
  • totalEurPrice 不可解析。
  • 你能给出totalEurPrice的输出吗?
  • 在您使用toFixed 之前,totalEurPrice 是否已经是一个数字(int、float)?只要确保所有数字确实是数字,而不是字符串:jsfiddle.net/x2qfeyop/2
  • 这里缺少太多信息。请尝试使用jsfiddle 制作问题的工作示例。

标签: javascript nan parsefloat


【解决方案1】:

正如每个人都说缺乏信息。所以我根据当前的统计数据做了一些假设。

i)var totalEurPrice=74.7888987;

ii)var numDecPoints=2;

 $(document).ready(function () {
    var xRate = $('#MainContent_lblCurrency').text();//Just check this once again,I am skeptical about this line.
    var totalEurPrice=74.7888987;
    var numDecPoints=2;
    alert("EXC Rate is " + xRate);//Pops up  1.23345
    totalEurPrice = totalEurPrice.toFixed(numDecPoints);
    alert("totalEurPrice is " + totalEurPrice);  //Pops up 74.79
    //now we divide to get GBP sales value
    var totalPrice = parseFloat(totalEurPrice) / parseFloat(xRate); 
    alert(totalPrice);//Pops up 60.63480481576068         
                           });

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2010-10-08
    • 2023-01-31
    相关资源
    最近更新 更多