How could I round a number to two decimal places? Looking through the docs, I see the (round:) macro, but that rounds to the nearest whole number, which isn’t what I want.
Have you tried to multiply a hundred fold, round, then divide a hundred fold?
Surprisingly, this is a hard problem due to how computers store fractional numbers.
If you’re trying to display a number with two decimal places, (digit-format "#####0.##", $your_number + 0.00501)
is probably good enough (maybe with a couple more zeroes between the 5 and the 1?).
If you’re just trying to round off the number to use it, then maybe (round: $your_number*100)/100
as @souppilouliouma suggests.
But note that neither of these is exactly correct. Read on for a brief introducion to the gory details
You know how one third is 0.33333… and it goes on forever? So if you multiply one third times three you might get 0.99999… instead of getting 1 back?
Computers, instead of storing tenths and hundredths and thousandths, store halves, quarters, eighths, and so on. This means that a lot more fractions end up being infinite approximations instead of being exact. For instance one tenth (0.1) is not exact.
So if you do 1.005 * 100, you’ll get 100.49999… and it’ll round to 100, and not 101 the way you want. So the last digit may be off by one with this approach. That may not be significant for you, but it’s something to be aware of.
The bigger problem (for display) is trailing zeroes: you’ll probably get 1 instead of 1.00 and 1.7 instead of 1.70.
Whenever possible, no matter what language you’re using, avoid using decimals. For instance, express US monetary values in cents rather than fractions of dollars. Whole numbers have no precision problems.