Rounding off numbers

Thoughts, Help, Feature Requests, Bug Reports, Developing code for...

Moderators: dorpond, trevor, Azhrei

Forum rules
PLEASE don't post images of your entire desktop, attach entire campaign files when only a single file is needed, or generally act in some other anti-social behavior. :)
Post Reply
nirkedar
Cave Troll
Posts: 52
Joined: Tue Sep 21, 2010 3:13 pm

Rounding off numbers

Post by nirkedar »

The following code: [H: broadcast(0.1 * 10)]

produces this: 1.0

Is there a function to have Maptool round off numbers nicely, i.e. the answer should simply be: 1 without any trailing digits.


User avatar
aliasmask
Deity
Posts: 8667
Joined: Tue Nov 10, 2009 6:11 pm
Location: Bay Area

Re: Rounding off numbers

Post by aliasmask »

nirkedar wrote:The following code: [H: broadcast(0.1 * 10)]

produces this: 1.0

Is there a function to have Maptool round off numbers nicely, i.e. the answer should simply be: 1 without any trailing digits.


If you use a decimal or if a decimal is calculation along the way, it will always display in decimal. But as wolph said, those functions will remove the decimal as well as [wfunc]strformat[/wfunc] options.

nirkedar
Cave Troll
Posts: 52
Joined: Tue Sep 21, 2010 3:13 pm

Re: Rounding off numbers

Post by nirkedar »

I know about ceiling, floor & round.
However they will round numbers off even when there is a legitimate fraction.
I need a function that will only truncate the trailing zeros.

nirkedar
Cave Troll
Posts: 52
Joined: Tue Sep 21, 2010 3:13 pm

Re: Rounding off numbers

Post by nirkedar »

Alrighty, had to manually write my own macro called TRUNCATE to remove trailing zeros. In case anyone is interested, here it is:

Code: Select all

[H: Number = ARG(0)]
[H: Fraction = Number - floor(Number)]
[H: Result = round(Number)]

[H, IF(Fraction>0), CODE: {
   [ size = length(Fraction)]
   [ lastDigit= substring(Fraction, size-1, size)]
   [ WHILE(lastDigit==0), CODE: {
      [ size = size - 1]
      [ lastDigit = substring(Fraction, size-1, size)]
   }]
   [ Fraction = substring(Fraction, 0, size)]
   [ Result = Result + Fraction]
}]

[H: macro.return = Result]


So if I ran:

[R: TRUNCATE(1.020)]
[R: TRUNCATE(1.00)]

The results will be
1.02
1

User avatar
aliasmask
Deity
Posts: 8667
Joined: Tue Nov 10, 2009 6:11 pm
Location: Bay Area

Re: Rounding off numbers

Post by aliasmask »

You can probably use some regex and [wfunc]replace[/wfunc] for a single line to remove trailing 0s.

Code: Select all

<!-- remove trailing 0s -->
[r: num = round(1.0200,4)]<br>
[r: newNum = replace(num,"[.]*0+\$","")]


Now if you don't give it a fraction then it will remove 0s of a whole number so you may want to add a check for that.

Post Reply

Return to “MapTool”