rate.go54 lines, 1.8 KB
| 1 | // Package fx is the arithmetic of currency conversion: minor units, exchange |
| 2 | // rates as exact decimals, and rounding that never pays out a fraction of a |
| 3 | // cent we don't have. |
| 4 | package fx |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | // RateDecimals is how many decimal places a Rate keeps: more than any provider |
| 13 | // quotes, even for yen to dinars, about 0.0020302. |
| 14 | const RateDecimals = 10 |
| 15 | |
| 16 | // one is 1, as a Rate: 10 to the power of RateDecimals. |
| 17 | const one = 10_000_000_000 |
| 18 | |
| 19 | // A Rate is how many units of one currency buy one unit of another, as an |
| 20 | // exact decimal: a whole number of ten-billionths. 0.9215 is 9_215_000_000. |
| 21 | // Never a float64: 0.1 has no exact binary value, and a tiny error, times a |
| 22 | // million dollars, is real money. |
| 23 | type Rate int64 |
| 24 | |
| 25 | // ParseRate reads a decimal like "0.9215", exactly. strconv.ParseFloat would |
| 26 | // round it to the nearest binary fraction first. |
| 27 | func ParseRate(s string) (Rate, error) { |
| 28 | whole, frac, _ := strings.Cut(s, ".") |
| 29 | if whole == "" || len(frac) > RateDecimals || strings.Trim(whole+frac, "0123456789") != "" { |
| 30 | return 0, fmt.Errorf("fx: invalid rate %q", s) |
| 31 | } |
| 32 | n, err := strconv.ParseInt(whole+frac+strings.Repeat("0", RateDecimals-len(frac)), 10, 64) |
| 33 | if err != nil || n == 0 { |
| 34 | return 0, fmt.Errorf("fx: invalid rate %q", s) |
| 35 | } |
| 36 | return Rate(n), nil |
| 37 | } |
| 38 | |
| 39 | // String writes r as a decimal, without trailing zeros: 0.9215. |
| 40 | func (r Rate) String() string { |
| 41 | s := fmt.Sprintf("%d.%0*d", r/one, RateDecimals, r%one) |
| 42 | return strings.TrimSuffix(strings.TrimRight(s, "0"), ".") |
| 43 | } |
| 44 | |
| 45 | // Rates travel as JSON strings, "0.9215": a JSON number is a float64 to most |
| 46 | // of the languages that read it. |
| 47 | func (r Rate) MarshalText() ([]byte, error) { |
| 48 | return []byte(r.String()), nil |
| 49 | } |
| 50 | |
| 51 | func (r *Rate) UnmarshalText(b []byte) (err error) { |
| 52 | *r, err = ParseRate(string(b)) |
| 53 | return err |
| 54 | } |