I am in the process of developing a cart system, and encountered some challenges with rounding certain amounts during calculations. Below are the details of my cart.
itemPrice = 0.99;
itemQuantity = 10;
totalPrice = 9.90; /* 0.99 * 10 */
here I apply 25% of discount coupon on the totalPrice amount
discountedPrice = 2.475 /* (9.90 * 25) / 100 */
totalPriceAfterDiscount = 7.425 /* 9.90 - 2.475 */
Please provide instructions on how to round the discountedPrice and totalPriceAfterDiscount amounts to two decimal places, ensuring that their sum equals the totalPrice.
Upon rounding both figures, the values are as follows: discountedPrice = 2.48 and totalPriceAfterDiscount = 7.43. The sum of 2.48 and 7.43 equals 9.91.
const afterDiscount = Math.round((7.425 + Number.EPSILON) * 100) / 100;
const discountedAmount = Math.round((2.475 + Number.EPSILON) * 100) / 100;
const total = afterDiscount + discountedAmount;
console.log(`afterDiscount: ${afterDiscount}`);
console.log(`discountedAmount: ${discountedAmount}`);
console.log(`total: ${total}`);
Rounding financial quantities introduces inaccuracies on the scale of tenths of cents. Just a couple of those will compound into the pennies and beyond.
What most financial systems (all?) do, is to only round outputs. Have all intermediate computations take full advantage of the available float precision -- 15 decimal places in JS.
The OP code prematurely rounds several intermediate calculations. By contrast, this code clearly delineates inputs and outputs, and rounds only the output...