【问题标题】:JS function that returns decimal format 1返回十进制格式1的JS函数
【发布时间】:2012-05-05 07:56:44
【问题描述】:

我编写了一个函数 to_money,以便对 sub_total 函数中的“价格”、“数量”和“总计”进行格式化并附加两个零 - 所以 2 变为 2.00 ,函数在这里:

 to_money: function(amount) {
      return Number(amount).toFixed(2) 
    },


sub_total: function() {
 var In = this
 return $$('.item').inject(0, function(sum, row) {
  var quantity = Number($F('Item' + row.id + 'Quantity'))
  var price = Number($F('Item' + row.id + 'Price'))
  var line_total = quantity * price
 $('Item' + row.id + 'Quantity').value = In.to_money(quantity) 
  $('Item' + row.id + 'Price').value = In.to_money(price)
  $('Item' + row.id + 'Total').update('£' + In.to_money(line_total)) In.to_money(line_total)) 
  return sum + line_total 
 })

我如何编写一个类似于格式化价格的函数“to money”的函数,而是一个格式化数量的函数,以确保在没有输入输入的情况下将默认小数 1 作为数量的前缀.

所以函数 sub_total 中的行将调用新函数以在数量上运行:

 $('Item' + row.id + 'Quantity').value = In.to_decimal(quantity) 

函数会是这个样子吗?

to_decimal: function(amount) {
          return Number(amount).toFixed(0) 
        },

【问题讨论】:

  • 不确定你的意思。我的解释是您希望将零/无值显示为 0.1?
  • 我正在尝试这样做,如果没有输入数量,js会自动添加十进制数1。
  • 你还没说“十进制数 1”是什么意思。是1.0吗?还是0.1?或者是其他东西? “1”本身不一定是十进制数:它是任何基数(包括二进制)的 1。

标签: javascript


【解决方案1】:

试试

to_decimal: function(amount) {
          var n = Number(amount);
          return (n && n>0 ? n : 1).toFixed(2);
}
In.to_decimal('');               //=> 1.00
In.to_decimal('bogusinput');     //=> 1.00
In.to_decimal(0);                //=> 1.00
In.to_decimal('23.1');           //=> 23.10
//note: Number autotrims the parameter
In.to_decimal('          45.3'); //=> 45.30

【讨论】:

  • 1..toFixed(2) 等价于'1.00'(也许更具可读性)。我会使用to_decimal: function(n) {return (n>0 ? 1*n : 1).toFixed(2);}
  • @Rob W:不是真的,return (n>0 ? 1*n : 1).toFixed(2); 有时会返回NaN,例如在In.to_decimal('bogusinput');
  • 我明白了。但以下是防水的:(n > 0 && 1*n || 1).toFixed(2)(保留无穷大值,("1e999"Infinity))。
  • 是的。看起来像微优化和选择/口味问题。在这两种情况下,“1e999”都会返回“Infinity”。如果你想防止这种情况发生,我想你也会检查n<Infinity
  • 如果你真的想确保你总是得到一个[nnn...].[nn]形式的字符串化数字,你会检查n<=1e20
猜你喜欢
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 2022-08-18
  • 2013-08-22
  • 1970-01-01
相关资源
最近更新 更多