Trim Number: Difference between revisions

From RPTools Wiki
Jump to navigation Jump to search
m (Initial Write-up.)
 
mNo edit summary
Line 1: Line 1:
{{TrustedFunction}}
''' ''Requires MapTool 1.3b56'' '''<br>
''' ''Requires MapTool 1.3b56'' '''<br>
The following is a user defined function that allows you to trim any trailing zeros from a floating point number(a number with decimal places). It also allows you to truncate the decimal places to a certain length and round any truncated decimal places in a certain direction.
The following is a user defined function that allows you to trim any trailing zeros from a floating point number(a number with decimal places). It also allows you to truncate the decimal places to a certain length and round any truncated decimal places in a certain direction.

Revision as of 23:49, 11 May 2009

Requires MapTool 1.3b56
The following is a user defined function that allows you to trim any trailing zeros from a floating point number(a number with decimal places). It also allows you to truncate the decimal places to a certain length and round any truncated decimal places in a certain direction.

Usage

trimNumber(number)
trimNumber(number, length)
trimNumber(number, length, direction)

Parameters:

  • number - The number to be trimmed.
  • length - How many decimal places the trimmed number should retain, defaults to 10.
  • direction - A string containing the direction that any truncated decimals placed should be rounded it. Accepts "up", "u", "down", and "d", defaults to rounding to the nearest.

Macros

Place the following macros on the same library token(or on different library tokens if you're know what you're doing and what to change).


onCampaignLoad

[defineFunction("trimNumber", "trimNumber@this", 1)]



trimNumber

[assert(argCount() != 0, "trimNumber() requires at least one parameter.")]
[assert(argCount() <= 3, "trimNumber() accepts a maximum of three parameters.")]
[NumberToTrim = arg(0)]
<!-- Set truncation depth -->
[if(argCount() >= 2), code:
{
    [TruncationDepth = power(10, arg(1))]
};{
    [TruncationDepth = power(10, 10)]
}]
<!-- Set rounding method -->
[if(argCount() == 3), code:
{
    [RoundingMethod = substring(arg(2), 0 , 1)]
};{
    [RoundingMethod = 0]
}]
<!-- Perform trim -->
[switch(RoundingMethod):
    case "u": NumberToTrim = ceiling(NumberToTrim*TruncationDepth)/TruncationDepth;
    case "d": NumberToTrim = floor(NumberToTrim*TruncationDepth)/TruncationDepth;
    default: NumberToTrim = round(NumberToTrim*TruncationDepth)/TruncationDepth
]
[macro.return = NumberToTrim]


Examples

[r: trimNumber(1.125000)]

Returns 1.125

[r: trimNumber(1.125000, 2)]

Returns 1.13

[r: trimNumber(1.124000, 2)]

Returns 1.12

[r: trimNumber(1.123000, 2, "up")]

Returns 1.13

[r: trimNumber(1.128000, 2, "down")]

Returns 1.12