Dynamic Number format function

Share your advanced PureBasic knowledge/code with the community.
User avatar
pdwyer
Addict
Addict
Posts: 2813
Joined: Tue May 08, 2007 1:27 pm
Location: Chiba, Japan

Dynamic Number format function

Post by pdwyer »

There is probably a function that does this but I can't find it.
There is probably also a more efficient way to do this.

Rather than write my own function from scratch, this is basically a wrapper function on FormatNumber() to trim the unwanted zeros off.
If I have a number where I want X decimal places if they exist but I don't want zeros if they don't, or if the number is not decimal then I don't even want a decimal point

4.21200 will become 4.212 without sacrificing or rounding longer numbers with actual decimals
12.0000 will become 12
0.0 will become 0

Some other languages do this with a "###,###.###" format and if there are no extra decimals it trims

Code: Select all

Procedure.s DynFormatNumber(Number.d,decimals.l)
    
    Define RawNumber.s
    Define i.l
    
    RawNumber = FormatNumber(Number,decimals,".",",")
    
    For i = decimals To 2 Step -1 
        If Right(RawNumber,i+1) = "." + ReplaceString(Space(i)," ","0")
            ProcedureReturn Left(RawNumber,Len(RawNumber)-(i+1))
        EndIf
    Next

    For i = decimals To 1 Step -1
        If Right(RawNumber,i) = ReplaceString(Space(i)," ","0")
            ProcedureReturn Left(RawNumber,Len(RawNumber)-i)
        EndIf
    Next

    ProcedureReturn RawNumber
        
EndProcedure

;==========================================================

;test

For i = 1 To 20
    a = Random(10)
    b = Random(10)
    
    Debug "DynFormatNumber:   " + DynFormatNumber(a/b,3)
    Debug "FormatNumber:      " + FormatNumber(a/b,3,".",",")
    Debug "StrD:              " + StrD(a/b,3)
    Debug "========"
    
Next
Paul Dwyer

“In nature, it’s not the strongest nor the most intelligent who survives. It’s the most adaptable to change” - Charles Darwin
“If you can't explain it to a six-year old you really don't understand it yourself.” - Albert Einstein
User avatar
pdwyer
Addict
Addict
Posts: 2813
Joined: Tue May 08, 2007 1:27 pm
Location: Chiba, Japan

Re: Dynamic Number format function

Post by pdwyer »

LOL :mrgreen: :oops:

There is a simpler way to do this

Code: Select all

RTrim(RTrim(FormatNumber(a/b,3,".",","),"0"),".")
:lol:

When I wrote the article above, I typed the word "trim" and thought.... hmmmm
Paul Dwyer

“In nature, it’s not the strongest nor the most intelligent who survives. It’s the most adaptable to change” - Charles Darwin
“If you can't explain it to a six-year old you really don't understand it yourself.” - Albert Einstein
Post Reply