Search code examples
javascriptparsingprintingnumbersrounding

Format number without rounding, limitimg decimal places, operate futher on number


I`d like to format decimal number 0.0003333333333333333 to 0.00033 without rounding. Number is coming from division decimal numbers. Also want to operate futher with number 0.00033.

toFixed(), Math.round(), toPrecision() are rounding so im not keeping eye on it.

I was thinking about parsing number to string, use slice and next parse text to number again.

Code:

let salesMixOld1 = document.querySelector("#sales-mix-old-1");
let cosOldPromo = document.querySelector("#cos-old-promo");
let salesMixOld2 = document.querySelector("#sales-mix-old-2");

let daysInMonth = document.querySelector("#days-in-month");
let howMuchDaysPromotion = document.querySelector("#how-much-days-promotion");

const calculateCosAll = () => {
    let parseCosAll = parseFloat(cosAll.value);
    let parseSalesMixOld1 = parseFloat(salesMixOld1.value);
    let parseCosOldPromo = parseFloat(cosOldPromo.value);
    let parseSalesMixOld2 = parseFloat(salesMixOld2.value);

    let resultCalculateCosAll = (parseCosAll - (parseCosOldPromo * parseSalesMixOld2)) / parseSalesMixOld1;

    calculatedCosAllDiv.innerHTML = resultCalculateCosAll;
}

const calculateSalesMixPerDay = () => {
    let parseSalesMixOld2 = parseFloat(salesMixOld2.value);
    let parsedaysInMonth = parseFloat(daysInMonth.value);
    let parsehowMuchDaysPromotion = parseFloat(howMuchDaysPromotion.value);

    let resultCalculateSalesMixMonth = parseSalesMixOld2 / parsedaysInMonth;
    let resultCalculateSalesMixDay = resultCalculateSalesMixMonth * parsehowMuchDaysPromotion;

    calculatedSalesMixDiv.innerHTML = resultCalculateSalesMixMonth + "/" + resultCalculateSalesMixDay;
}


calculateCosAllBtn.addEventListener('click', calculateCosAll);
calculateSalesMixBtn.addEventListener('click', calculateSalesMixPerDay);

Solution

  • To avoid rounding you can multiply by the appropriate power of 10, call Math.trunc() which will return the integer part of a number discarding the decimal, and then divide again.

    const input = 0.000338;
    const result = Math.trunc(input * 100_000) / 100_000;
    
    console.log(result);

    Or as a helper function

    function truncate(number, places) {
      return Math.trunc(number * 10 ** places) / 10 ** places;
    }
    
    const input = 0.000338;
    console.log(truncate(input, 5));