Line data Source code
1 : package consts
2 :
3 : import (
4 : "fmt"
5 : )
6 :
7 : // Currency は所持金や価格などの金額。整数で正確に扱い、表示整形は String に閉じる。
8 : // float の丸め誤差を避けるため加減算と比較はこの整数で行う。
9 : // 重量 Milligram と同じ設計で、単位取り違えを型で弾くために素の int と区別する。
10 : type Currency int
11 :
12 : // String はカンマ区切りと通貨記号で整形する。3桁ごとにカンマを入れ、負値は先頭に符号を付ける。
13 : func (c Currency) String() string {
14 1 : str := fmt.Sprintf("%d", int(c))
15 1 :
16 1 : negative := false
17 1 : if c < 0 {
18 1 : negative = true
19 1 : str = str[1:]
20 1 : }
21 :
22 1 : var result string
23 1 : for i, ch := range str {
24 1 : if i > 0 && (len(str)-i)%3 == 0 {
25 1 : result += ","
26 1 : }
27 1 : result += string(ch)
28 : }
29 :
30 1 : if negative {
31 1 : result = "-" + result
32 1 : }
33 :
34 1 : return fmt.Sprintf("%s %s", IconCurrency, result)
35 : }
|