【问题标题】:Insert number in Meteor Collection在流星集合中插入数字
【发布时间】:2016-02-15 01:43:37
【问题描述】:

我想将一个变量作为数字插入到我的 Meteor 集合中。但是,当我签入客户端控制台和迷你 mongodb 控制台时,它们被保存为字符串。

这是我的代码:

Gifts.insert({
    category : t.find('#selectCat').value,
    amount : parseFloat(inputAmount).toFixed(2),
    desc : description,
    createdAt : new Date(),
    createdBy : Meteor.user().username
});

我也试过amount : Number(inputAmount).toFixed(2),但也没有用。

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    这就是我解决问题的方法。

    我将金额作为数字插入Number(inputAmount):

    Gifts.insert({
        category : t.find('#selectCat').value,
        amount : Number(inputAmount),
        desc : description,
        createdAt : new Date(),
        createdBy : Meteor.user().username,
    });
    

    然后,我创建了一个助手来格式化在 html 中呈现时的金额:

    Handlebars.registerHelper("formatAmount", function(str) {
        return str.toFixed(2);
    });
    

    在渲染期间我这样做:{{formatAmount amount}}

    【讨论】:

      【解决方案2】:

      toFixed 方法将数字转换为格式化字符串。只需将其删除,以便您的变量保持为数字。

      【讨论】:

      • 我试图从输入文本字段中获取值并将它们格式化为有两位小数并分配给我的“var inputAmount”。格式化后,我插入到集合中。有没有办法格式化'inputAmount'?
      【解决方案3】:

      改变

      amount : parseFloat(inputAmount).toFixed(2) 
      

      到

      amount : parseFloat(inputAmount).round(2) 
      

      使返回值仍然是一个小数点后 2 位的数字。

      第二个

      amount : Number(inputAmount);
      

      可能你需要这样做:

      amount : new Number(inputAmount);
      

      【讨论】:

      • parseFloat(inputAmount).round(2) 将有一个undefined is not a function。
      猜你喜欢
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      相关资源
      最近更新 更多