Home > Net >  Custom Rounding Ranges using Javascript?
Custom Rounding Ranges using Javascript?

Time:10-09

I'm a corporate trainer for a retailer, not a developer, but I need to figure out some coding to finish up a project. Thanks for any help!

Working on a project to calculate sales prices for beer that figures in cost, markup, deposit, and discounts. Info is submitted at store level through a web form, that data auto-populates in a pdf form, and that form is then sent to the buyer. This javascript is being written into that pdf file.

Where I'm stuck is that I need to round the final sale price using specific rules to match our pricing structure. Here's the rules:

  • If the last 2 digits are in the range of 00 and 19, round down to nearest 99.
  • If the last 2 digits are in the range of 20 and 69, round up to nearest 09.
  • If the last 2 digits are in the range of 70 and 99, round to 99.

So:

  • 5.19 needs to round down to 4.99.
  • 21.20 needs to round up to 22.09.
  • 102.76 needs to round to 102.99.

I'm just lost and confused at this point, I'm already well out of my depth. Here's where I've gotten so far:

var flsellround = this.getField("FLSellCalc").value;
var lasttwo = flsellround.slice(0, -2);

...and I don't know where to go from there, or even if using .slice is the correct next step. The field containing the number that needs to be rounded is "FLSellCalc".

Hopefully that all makes sense. Anyone able and willing to help me out here? I'd sure appreciate it!

CodePudding user response:

Here is a function and an interactive page to test it:

function specialRound(n) {
    if (n < 0) return -specialRound(-n);
    let decimals = n % 1;
    return n - decimals   
         ( decimals < 0.2 ? -0.01
         : decimals < 0.7 ? 1.09
         : 0.99);
}

let output = document.getElementById("output")
let flsellinput = document.getElementById("FLSellCalc");
flsellinput.addEventListener("input", refresh);

function refresh() {
    let n =  flsellinput.value;
    output.textContent = specialRound(n);
}
refresh();
<input id="FLSellCalc" type="number" value="5.19" step="0.01">

<div id="output"></div>

  • Related