Created
May 4, 2014 05:52
-
-
Save jots/11511274 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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