Code archives/Miscellaneous/Number Format

This code has been declared by its author to be Public Domain code.

Download source code

Number Format by dmaz2006
commas and left padding are optional. there is error checking for negative parameters. padding specifies how many characters will be on left of the decimal. any string that exceeds (padding + decimal + decimal places) will output "Error"

Output:
   123,456,789.00

 1,234,567,891.23
    12,345,678.91
       123,456.78

  123456789123.00
            Error
Print Format(123456789:Double,2,3,14)
Print
Print Format(1234567891.23:Double,2,3,14)
Print Format(12345678.9123:Double,2,3,14)
Print Format(123456.789123:Double,2,3,14)
Print
Print Format(123456789123:Double,2,0,14)
Print Format(123456789123:Double,2,3,14)

Function Format:String( number:Double, decimal:Int=4, comma:Int=0, padleft:Int=0 )
	Assert decimal > -1 And comma > -1 And padleft > -1, "Negative decimal,comma or padleft not allowed in Format()"

	Local str:String = number
	Local dl:Int = str.Find(".")
	If decimal = 0 Then decimal = -1
	str = str[..dl+decimal+1]
	If comma
		While dl>comma
			str = str[..dl-comma] + "," + str[dl-comma..]
			dl :- comma
		Wend
	EndIf
	If padleft
		Local paddedLength:Int = padleft+decimal+1
		If paddedLength < str.Length Then str = "Error"
		str = RSet(str,paddedLength)
	EndIf
	Return str
End Function

Comments

dmaz2006
fixed bug; if decimal was 0 it would print the decimal


Code Archives Forum