Ad

Rounding Down A Value By A Variable Amount

- 1 answer

So, I am writing a crypto trading bot. I can work out how much of ETH I can buy with the BTC I have, but you can only buy ETH in incremental values. The increments would range from 1000 to 0.001 depending on coin.

Question is how do I round 123.456789 down to 123.456 if the increment is 0.001 and 120 if the increment is 10.

Edit-The other question suggested was with a fixed number of DP while this was variable.

Ad

Answer

Assuming that increment values are powers of ten, positive or negative, the algorithm for this is as follows:

  • Divide the value by the increment
  • Truncate the decimal portion of the result
  • Multiply truncated value by the increment

Multiplying by a power of ten "shifts" the position of the decimal point by the number of digits equal to the power by which you multiply. Doing so positions the part that you want to truncate after the decimal point.

public static decimal RoundDown(decimal val, decimal pos) {
    return pos * Math.Truncate(val / pos);
}

Note that this approach works for increments both above and below 1. When the increment is 10, dividing yields 12.3456789, truncation yields 12, and multiplying back yields the desired value of 120.

Demo.

Ad
source: stackoverflow.com
Ad