Jump to content
Sign in to follow this  
Zinthose

StringToPercent("99.3%")

Recommended Posts

Zinthose

I wrote this function for a UDF I'm working on and decided to share as I'm sure it would be useful to someone. ;)

It has a range of: 0.01% to 100% including 0%.

#Region : Example

    Example()

    Func Example()
        Local $Prompt = "100%"
        Local $Message = "StringToPercent Function Example\n\n\tValue\t= %s\n\tPercent\t= %s\n\tError\t= %i"
        Local $Value = 1
        Local $Err = 0
        Local $DecimalPlaces = 2
        
        $DecimalPlaces = Number(InputBox('StringToPercent', "Please define the number of decimal places to allow.", $DecimalPlaces))
        
        While $Prompt <> ""
            $Value = StringToPercent($Prompt)
            $Err = @error
            
            $Prompt = InputBox('StringToPercent("' & $Prompt & '", ' & $DecimalPlaces & ')', StringFormat($Message, $Value, $Prompt, $Err), $Prompt)
        WEnd
    EndFunc
#EndRegion

;## Convert a string percent value to a decimal equivalent
;## Examples:
;##         StringToPercent("0%")               = 0,        @error = 0
;##         StringToPercent("99.99%")           = 0.9999
;##         StringToPercent("100%")             = 1
;##         StringToPercent("99.9999%", -1)     = 0.999999
;##         StringToPercent("101%")             = 0,        @error = 2
;##         StringToPercent("99.999%")          = 0,        @error = 2
;##         StringToPercent(99)                 = 0,        @error = 1
;##         StringToPercent("99")               = 0,        @error = 2
;##         StringToPercent("99.99%", 0)        = 0,        @error = 2
;##         StringToPercent("99.99%", "2")      = 0,        @error = 3
;##         StringToPercent("99.99%", 0.1)      = 0,        @error = 4
;##         StringToPercent("99.99%", -2)       = 0,        @error = 4
;## Errors:
;##         @error = 1 : $Percent is not a string value
;##         @error = 2 : $Percent failed regular expression
;##         @error = 3 : $DecimalPlaces is not a numeric value
;##         @error = 4 : $DecimalPlaces value is outside acceptable range. [Negative One -OR- Greater Than or Equal To Zero Or -1]
Func StringToPercent($Percent, $DecimalPlaces = Default)
    Local $RegEx_Percent ;= "\A(100(?:\.0{1,2})?|0*?\.\d{1,2}|\d{1,2}(?:\.\d{1,2})?)%\z"; <== Original RegExp for Reference
    
    ;## Validate $DecimalPlaces
    If $DecimalPlaces = Default Then $DecimalPlaces = 2
    If Not IsNumber($DecimalPlaces) Then Return SetError(3, 0, 0)
    $DecimalPlaces = Int($DecimalPlaces)
    
    ;## Build Regular Expression
    Select
        Case $DecimalPlaces = 1
            $RegEx_Percent = "\A(100(?:\.0{1})?|0*?\.\d{1}|\d{1,2}(?:\.\d{1})?)%\z";    <== 0.1%, 50.5%, 100.0%
        Case $DecimalPlaces > 1
            $RegEx_Percent = "\A(100(?:\.0{1," & $DecimalPlaces & "})?|0*?\.\d{1," & _
                $DecimalPlaces & "}|\d{1,2}(?:\.\d{1," & $DecimalPlaces & "})?)%\z";    <== 0.01%, 50.55%, 100.00%
        Case $DecimalPlaces = 0
            $RegEx_Percent = "\A(100|0*?|\d{1,2})%\z";                                  <== 0%, 50%, 100%
        Case $DecimalPlaces = -1
            $RegEx_Percent = "\A(100(?:\.0+)?|0*?\.\d+|\d{1,2}(?:\.\d+)?)%\z";          <== 0.0000001%, 50.54872658%, 100.00000000%
        Case Else
            Return SetError(4, 0, 0); <== $DecimalPlaces value is outside acceptable range. [Negative One -OR- Greater Than or Equal To Zero Or -1]
    EndSelect
    
    ;## Validate $Percent
    If Not IsString($Percent) Then Return SetError(1, 0, 0);                        <== If it's not a string it's not a percent: @error = 1
    If Not StringRegExp($Percent, $RegEx_Percent) Then Return SetError(2, 0, 0);    <== If the Regular Expression failed then it's not a percent: @error = 2
    
    $Percent = StringTrimRight($Percent, 1);                <== Remove the trailing percent sign
    $Percent = Number($Percent);                            <== Convert String to Numeric Value
    If $Percent > 0 Then $Percent = Number($Percent) / 100; <== Convert the percent value to its decimal equivalent
    
    Return $Percent
EndFunc

Edit: Added Example Code

Edited by Zinthose

--- TTFN

Share this post


Link to post
Share on other sites
Zinthose

Did a full rewrite to allow for parameter defined decimal places and added an example.


--- TTFN

Share this post


Link to post
Share on other sites
Xenobiologist

Hi,

why should I not just use StringFormat?

$str = 45.78
ConsoleWrite(_StringPercent($str) & @CRLF)
ConsoleWrite(_StringPercent($str, 6, 2) & @CRLF)
ConsoleWrite(_StringPercent($str, 6, 3) & @CRLF)
ConsoleWrite(_StringPercent($str, 7, 3) & @CRLF)
ConsoleWrite(_StringPercent($str, 4, 1) & @CRLF)
ConsoleWrite(_StringPercent($str, 5, 1) & @CRLF)

Func _StringPercent($str, $stringLength = 5, $decimal = 2)
    Return StringFormat("%0" & $stringLength & "." & $decimal & "f%%", $str)
EndFunc   ;==>_StringPercent

Mega

Edited by Xenobiologist

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Share this post


Link to post
Share on other sites
Zinthose

@Xenobiologist [AKA=Mega]

The StringToPercent function was written to start with a supplied variable typically from a user entered field that you want to validate and convert the supplied percentage string to a decimal equivalent.

The example you provided assumes the value as valid and converts the decimal value to a string percent for display purposes.

Example:

  • We have 50 Apples.
  • We prompt the user for how many apples they want.
  • User enters 25%
  • We validate and convert the supplied value of "25%" to 0.25
  • 0.25 * 50 = 12
  • We give user 12 Apples.
Global $Apples = 50

$Request = InputBox("AppleSeed", StringFormat("We have %d Apples\n\n\tHow many apples do you want?",$Apples))

If StringIsDigit($Request) Then
    If Int($Request) > $Apples Then
        MsgBox(0, "AppleSeed", "I'm sorry we don't have enough apples.")
        Exit
    EndIf
ElseIf StringToPercent($Request) Then
    $Request = StringToPercent($Request) * $Apples
EndIf

MsgBox(0, "AppleSeed", StringFormat("Here are your %d Apples.", $Request))

;## Be Sure to add the StringToPercent function here.  ^_^

--- TTFN

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.