0

I know similar questions get asked here frequently, but I've not been able to find an answer that I've been able to make work after searching for a couple hours; could really use your help.

Working on a pricing calculator using Javascript in Adobe Acrobat and I need to limit a number to exactly 2 decimal places without any rounding.

I need to limit the decimal places because the next step in the calculator is to adjust that number to fit in our pricing structure based on where its decimals fall within a range. Here's my adjustment code for some context.

if (decimals < 0.20)event.value = -1.01;
else if ((decimals > 0.19) && (decimals < 0.30))event.value = 0.29;
else if ((decimals > 0.29) && (decimals < 0.40))event.value = 0.39;
else if ((decimals > 0.39) && (decimals < 0.50))event.value = 0.49;
else if ((decimals > 0.49) && (decimals < 0.60))event.value = 0.59;
else if ((decimals > 0.59) && (decimals < 0.70))event.value = 0.69;
else event.value = 0.99;

The problem arises when I have a value of, for example, 15.390001. I need that adjustment code to return 15.39, but right now it's being pushed to 15.49, since x.390001 is greater than x.39.

Currently using the code below to truncate a number to 2 decimal places without rounding.

var flcost = this.getField("fl_cost"); // Front Line Cost
var multi = this.getField("multiplier_calc"); // Subcat Multiplier
var dep = this.getField("deposit"); //Deposit total

var nAdj = Math.pow(10, 2); // decimal adjustment

var rough = Math.floor(flcost.value * multi.value * nAdj) / nAdj;
event.value = rough+deposit;

I'm getting inconsistent values returned. For instance, it will correctly truncate 11.376 down to 11.37, and 9.432 down to 9.43.

However, when I feed it something like 23.832, it's returning 23.830000000000002, and in another case, when fed 143.832, it's returning 143.82999999999998. In other cases I've seen it actually rounding up, so I'm just incredibly confused.

So, what do I need to do to properly cut a number down to 2 decimal places without rounding?

And sorry for potentially over-explaining things!

Jake
  • 3
  • 3
  • Quick workaround: you can -0.05 and round then. As for "when I feed it something like 23.832, it's returning 23.830000000000002, and in another case, when fed 143.832, it's returning 143.82999999999998" - that's how floats work. (See also questions on why 0.1+0.2 is not 0.3) You might want to use some sort of decimals to deal with that, or even manually work on integers and just putting the decimal place down manually between digits. [I don't do js, I came here from the reopen queue. Btw, love your edit reason, really helps to cast my vote. :)] – h4z3 Oct 26 '21 at 08:46

0 Answers0