简体   繁体   中英

How to find a 10% discount of all elements in a JavaScript array

How do I find the discounted price of all the elements? The discount should be 10%

Here is what I have attempted:

    var arr = [299.99, 399.99, 599.99, 799.99]
    arr.forEach((value, index) => {
    arr[index] * (10/100)

});

Map it

  var discount = arr.map(el => el * 0.9);

If you want 2 decimals use toFixed(2)

  var discount = arr.map(el => (el * 0.9).toFixed(2));

The values will convert to string. So parse it back

   var discount = arr.map(el => parseFloat((el * 0.9).toFixed(2)));

When working with money you should use pennies to avoid loss of precision errors.

The following uses Array#Map to calculate the discounted price, and then Number#toFixed to round it to the nearest penny. If this is for production code, then you need to make absolutely sure that this type of rounding is permitted.

 var arr = [299.99, 399.99, 599.99, 799.99] const discount = (arr) => arr.map((el) => (el - el * (10/100)).toFixed(2)) console.log(discount(arr))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM