Drill

ProblemsGo › pricing

Format money for a receipt

mediumpricingStringsMathGo

The receipt printer takes a plain string. Amounts arrive in minor units and have to come out grouped and signed the way finance expects.

formatMoney(minor: int) → string

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func formatMoney(minor int) string {
	
}

Worked examples

CallResult
formatMoney(123456)"1,234.56"
formatMoney(0)"0.00"
formatMoney(5)"0.05"
formatMoney(-50)"(0.50)"

Hint

Split into whole and remainder first, build the grouped whole part, then glue on the sign.

Reference solution in Go
func formatMoney(minor int) string {
	neg := minor < 0
	abs := minor
	if abs < 0 {
		abs = -abs
	}
	whole := strconv.Itoa(abs / 100)
	cents := strconv.Itoa(abs % 100)
	if len(cents) < 2 {
		cents = "0" + cents
	}
	grouped := ""
	for i := 0; i < len(whole); i++ {
		if i > 0 && (len(whole)-i)%3 == 0 {
			grouped += ","
		}
		grouped += string(whole[i])
	}
	body := grouped + "." + cents
	if neg {
		return "(" + body + ")"
	}
	return body
}

The same problem in another language

More pricing problems in Go