Reputation: 347
I have written a function to_money so that 'Price' 'Quantity' and 'Total' in the sub_total function are formatted and two zeroes attached - so 2 becomes 2.00, the function is here:
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
})
How do I write a function that is similar to the function 'to money' that formats the price, but instead a function that formats the quantity for making sure a default decimal of 1 is prefixed to the quantity if no input is entered.
so the line in function sub_total would call the the new function to run on quantity:
$('Item' + row.id + 'Quantity').value = In.to_decimal(quantity)
Would the function look like this?
to_decimal: function(amount) {
return Number(amount).toFixed(0)
},
Upvotes: 4
Views: 447
Reputation: 122986
try
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
Upvotes: 3