Skip to content

Instantly share code, notes, and snippets.

@Demitroi
Created March 11, 2019 19:32
Show Gist options
  • Save Demitroi/7058372cb6eb0294c437bfa0f4003935 to your computer and use it in GitHub Desktop.
Save Demitroi/7058372cb6eb0294c437bfa0f4003935 to your computer and use it in GitHub Desktop.
Just a function to format float64 to money in Golang :)
package main
import (
"fmt"
"math"
"strings"
)
func main() {
var money float64 = 6922850.56
fmt.Println(fmtMoney(money, 2))
money = 0
fmt.Println(fmtMoney(money, 2))
money = 1
fmt.Println(fmtMoney(money, 2))
money = 18
fmt.Println(fmtMoney(money, 4))
money = 18.5641862
fmt.Println(fmtMoney(money, 6))
money = 123
fmt.Println(fmtMoney(money, 0))
money = -123
fmt.Println(fmtMoney(money, 1))
money = 123.75
fmt.Println(fmtMoney(money, 2))
money = 3123.75
fmt.Println(fmtMoney(money, 2))
money = -3123.75
fmt.Println(fmtMoney(money, 6))
money = 48621
fmt.Println(fmtMoney(money, 2))
money = -48621.99
fmt.Println(fmtMoney(money, 4))
money = 100000
fmt.Println(fmtMoney(money, 2))
money = 109850.346
fmt.Println(fmtMoney(money, 2))
money = 1098500
fmt.Println(fmtMoney(money, 4))
money = 999999999.99
fmt.Println(fmtMoney(money, 2))
money = 0
fmt.Println(fmtMoney(money, 0))
}
func fmtMoney(v float64, d uint) string {
var sign, decimals string
if v < 0 {
sign = "-"
v = math.Abs(v)
}
places := fmt.Sprintf("%d", d)
tmp := fmt.Sprintf("%."+places+"f", v)
splited := strings.Split(tmp, ".")
if len(splited) > 1 {
decimals = splited[1]
} else {
decimals = ""
}
integers := splited[0]
var retval string
for i := len(integers); i > 0; i -= 3 {
if i-3 <= 0 {
retval = integers[0:i] + retval
break
}
retval = "," + integers[i-3:i] + retval
}
retval = sign + retval
if len(decimals) > 0 {
retval += "." + decimals
}
return retval
}
@Demitroi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment