【问题标题】:Working with a number stored as a string处理存储为字符串的数字
【发布时间】:2012-07-20 09:00:26
【问题描述】:

我猜这个问题在 CoffeScript 和 JavaScript 中很常见。在我的 CoffeeScript 脚本中,我通过 websocket 收到了一个类似 606.0 的数字。因此它以字符串的形式出现,从主机到达的 JSON 中提取。现在我想使用这个数字,比如说,添加一些东西,比如:

# @x is the number presented as a string
@xx = @x + 100
console.log("res=" + @xx)

我得到的是:

res=606.0100

所以它被添加为一个字符串!如果我稍微修改一下代码,“说”100 是浮点数:

# @x is the number presented as a string
@xx = @x + 100.0
console.log("res=" + @xx)

结果还是一样。

我的问题是 - 如何向 CoffeScript/JavaScript 解释这是一个数字,而不是一个字符串?

【问题讨论】:

    标签: javascript json coffeescript websocket


    【解决方案1】:

    要从字符串中转换数字,只需在前面加上 +:

    n = '100'
    alert n + 1 # 1001
    alert +n + 1 # 101
    

    http://jsfiddle.net/elclanrs/d77uq/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多