Reputation: 194
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.
Upvotes: 0
Views: 362
Reputation: 46
You can use floor:
double val = (double)Math.Floor(originalValue / increment) * increment;
Using
Math.Floor(originaValue / increment)
gives the amount of "crypto unit" that you can spend and then you multiply by increment to have the total of "crypto unit".
Upvotes: 0
Reputation: 726499
Assuming that increment values are powers of ten, positive or negative, the algorithm for this is as follows:
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.
Upvotes: 1