Comma seperated number

BlitzMax Forums/BlitzMax Beginners Area/Comma seperated number

AD(Posted 2007) [#1]
I'm looking for a function to seperate numbers with commas, to make it human readable.

ie:
999,999,999

Does anyone have this to hand?

Many thanks.


CS_TBL(Posted 2007) [#2]
would the input be an int or string?

-never mind, almost done-


CS_TBL(Posted 2007) [#3]
SuperStrict

Function CommaNumber$(v:Int,div$=",")
	Local s$=v
	If s$="" Return ""
	Local n$
	For Local t:Int=Len(s$)-1 To 0 Step -1
		n=Mid(s,1+t,1)+n
		If t And Not ((Len(s)-t) Mod 3) n=div+n			
	Next
	Return n
End Function

Function CommaString$(s$,div$=",")
	If s$="" Return ""
	Local n$
	For Local t:Int=Len(s$)-1 To 0 Step -1
		n=Mid(s,1+t,1)+n
		If t And Not ((Len(s)-t) Mod 3) n=div+n			
	Next
	Return n
End Function


Print CommaString("1")
Print CommaString("12")
Print CommaString("123")
Print CommaString("1234")
Print CommaString("12345")
Print CommaString("123456")
Print CommaString("1234567"," ")
Print CommaString("12345678",".")

Print CommaNumber(10001001,".")

End




JazzieB(Posted 2007) [#4]
Here's my solution...
Function FormatNumber:String(num:String)
	Local i:Int=num.Length-1,j:Int=0,out:String
	Repeat
		out=Chr(num[i])+out
		i:-1
		j:+1
		If j=3 And i>=0 Then
			out=","+out
			j=0
		EndIf
	Until i<0
	Return out
EndFunction

Local num:Int=1

For Local i:Int=1 Until 11
	Print FormatNumber(num)
	num:*10
Next

No need for seperate functions for numbers or strings, as they will all get converted to a string when passed to the function.


AD(Posted 2007) [#5]
That's great! Thanks for this!


FlameDuck(Posted 2007) [#6]
Whoa. Just use a StringTokenizer (if you want one value at a time) / Splitter (if you want all the values in an array). There are (litterally) hundreds in the Code Archives.


Brucey(Posted 2007) [#7]
None of those seem to work for real numbers :

Local num:Float=115600.12

Print FormatNumber(num)

1,156,00.,117


Oh well... I guess it's close enough :-)


dmaz(Posted 2007) [#8]
I put one in the code archives almost a year ago that does what you want.
http://www.blitzbasic.com/codearcs/codearcs.php?code=1790


JazzieB(Posted 2007) [#9]
None of those seem to work for real numbers


It was never intended to. I use it to display a player's score. AD seems satisfied, otherwise they would have mentioned they needed it to display floats.