Skip to content

Instantly share code, notes, and snippets.

@jots
Created May 4, 2014 05:52
Show Gist options
  • Save jots/11511274 to your computer and use it in GitHub Desktop.
Save jots/11511274 to your computer and use it in GitHub Desktop.
import strutils
# use mod == 0 a lot...
proc mod0(a,b:int):bool = (a mod b) == 0
# if i try to add to "result" directly I get a SIGSEGV
# so use "res" instead. why?
# oh yeah and there's probably a much better way to do this...
proc addCommas(s:string): string =
var
slen = s.len
res = ""
x = 0
for i in countDown(slen-1,0):
x.inc
res = s[i] & res
if i > 0 and x.mod0(3): res = ',' & res
return res
proc commify(n:int): string = addCommas($n)
# how to get numer of decimal places
# in the float passed in? right now we force it to 2.
proc commify(n:float): string =
var parts = split(formatFloat(n,ffDecimal,2),'.')
addCommas(parts[0]) & '.' & parts[1]
proc commify(s:string): string =
if s.find(".") == -1:
return addCommas(s)
else:
return commify(s.parseFloat)
echo commify(1_000_000_000)
echo commify(1236790.12)
echo commify("123123123")
echo commify(12)
echo commify("123123123.12")
echo commify("1234.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment