JS function that returns decimal format 1

I wrote the to_money function, so the “Price”, “Quantity” and “Total” in the sub_total function are formatted and two zeros are attached - so 2 will become 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 to write a function that looks like a cash-in function that formats the price, but instead a function that formats the quantity to make sure the default decimal digit is 1, is added to the quantity if no input is entered,

therefore, the line in the sub_total function will call a new function to run by quantity:

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

Will the function look like this?

 to_decimal: function(amount) { return Number(amount).toFixed(0) }, 
+4
source share
1 answer

to 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 
+3
source

Source: https://habr.com/ru/post/1410824/