How to round a number to the third decimal place?

Hi! I was wondering if it was possible to round a number to the third decimal rather than the nearest whole digit.

In case it’s not possible to achieve it, I think I could find a workaround, but it would save me a lot of time to actually be able to round numbers to the third (or second, or even first) decimal. Thanks.

1 Like

To answer your question: no, as far as I’m aware there isn’t a function for it. That said, this is a pretty fast workaround if you only need the code a few times:

*create var 3.05
*set var * 10
*set var round(var)
*set var / 10
value of var: ${var}

Output: “value of var: 3.1”


I also coded a *gosub routine for rounding to the first decimal digit — give me a sec and I can make one that works for any amount of decimal digits, if that’s something you would be interested in.

The subroutine:

*label round_dec_1
*params varname
*set {varname} * 10
*set {varname} round({varname})
*set {varname} / 10
*return

The main code:

*create var 3.05
*gosub round_dec_1 "var"
value of var: ${var}

Same output as above.


Edit: More general subroutine as promised!

*label round_dec
*params varname digits
*temp ten_power 1
*temp times 0
*label multiplication
*set ten_power * 10
*set times + 1
*if (times < digits)
    *goto multiplication
*set {varname} * ten_power
*set {varname} round({varname})
*set {varname} / ten_power
*return

And the main code:

*create var 3.01234
*gosub round_dec "var" 3
value of var: ${var}

This rounds var to 3.012.


Edit 2: Thanks to @cup_half_empty, who has kindly informed me of the existence of the power operator (^), I’ve edited the general subroutine a bit — it looks like this now:

*label round_dec
*params varname digits
*temp ten_power (10 ^ digits)
*set {varname} * ten_power
*set {varname} round({varname})
*set {varname} / ten_power
*return

Works exactly the same as the above subroutine, just with less lines!

8 Likes

:flushed: thank you SO much, this is more than I could have ever asked for!

2 Likes

That’s really nice. But you don’t need to loop a multiplication. That’s what the power operator is for.

This lines:

Can become:

*set {varname} * (10 ^ digits) 
5 Likes

Oh man, I had no idea there even was a power operator! (I tried ** instead of ^ and when that didn’t work gave up… price you get for rushing, haha.) Thank you for pointing that out!

1 Like

Yeah, I awalys forget it’s ^ instead of **. :joy:

1 Like

More hidden undocumented features. Power? What will we find next, hidden in CS? Hyperbolic trigonometry functions?

4 Likes

Not hidden, undocumented. :joy:

1 Like

The ^ operator is documented here, and has been for a long time:

2 Likes

1 Like

There is log too! Thanks for the info!

1 Like