# Rounding Down A Value By A Variable Amount

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.

## 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.

## Related Questions

- → How to Fire Resize event after all images resize
- → JavaScript in MVC 5 not being read?
- → URL routing requires /Home/Page?page=1 instead of /Home/Page/1
- → Getting right encoding from HTTPContext
- → How to create a site map using DNN and C#
- → I want integrate shopify into my mvc 4 c# application
- → Bootstrap Nav Collapse via Data Attributes Not Working
- → Shopify api updating variants returned error
- → Get last n quarters in JavaScript
- → ASP.NET C# SEO for each product on detail page on my ECOMMERCE site
- → SEO Meta Tags From Behind Code - C#
- → onchange display GridView record if exist from database using Javascript
- → How to implement search with two terms for a collection?