A Subroutine That Rounds to Any Number of Decimal Places

The ROUND function in KM only rounds off—1.5762 becomes 2. I was doing some stuff with weights in grams, and that level of rounding was too much. I searched the forums, but only found a couple threads that mentioned the usual trick (multiply by 10, round, divide by 10), but I didn't want to have to modify every variable I wanted to round off...and I wanted the ability to set the precision without having to edit 10 to 100 or 1000, etc.

So I developed a general subroutine (v10+) that will round any number to any specified number of decimal places. You pass it the number to be rounded, and the desired precision, and it does the rest.

s-RoundToDecimal_2.kmmacros (4.4 KB)

The only thing I can't figure out is how to force format zeros if the number is even—so 72 becomes 72.00, for example. The "use format" option on variable calculations would be ideal, but the input box only accepts formats, not variables that hold a format, so I can't make that work.

I think I can do it with a MOD and a repeat step to add some zeros, but I haven't bothered with that just yet. If anyone has suggestions, I'd love to hear them.


1 Like

I think you can work around that limitation by using a Switch statement that has a different entry for each possible number of digits. It's not a big deal to handle 15 different cases (I presume you will never need more than 15 decimals.)

Yea, I thought about that, but the purist in me hates giving up on the "any precision" aspect of the subroutine—even though I know almost nobody will ever use anything above three or four :). So I'll mull it over some more and see what I can come up with.

I've asked Peter to add decimals to the round function, which would make this all superfluous.

A programmer's life is filled with hacks to accommodate deficiencies in the tools he's using. I stopped being a purist years ago.

In fact, I like hacks, as it keeps me employed, because I'm the only person among my peers who can do some things.

Got it, and it was simpler than I was thinking it would be. Added the two highlighted steps, and now the macro pads to the proper number of zeros if the result is even.

If the difference between the truncated number and the whole number is zero, then it's an even result. And I already had the zeros stored because they're needed to set the scaling factor. Bingo!

I replaced the linked macro in the original post with the updated version.


1 Like

Good catch.

Hmm, I wonder what the opposite of a "purist" is. I think I'm an "impurest." I'll do whatever it takes to get the job done, including getting impure and using dirty tricks. Maybe I should change my name to Loki. Who else is known for dirty tricks?