summaryrefslogtreecommitdiff
path: root/format.go
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2017-05-21 15:02:35 +0200
committerDimitri Sokolyuk <demon@dim13.org>2017-05-21 15:02:35 +0200
commit64a507e2f19fc1ed9dab7f8123b334067d107533 (patch)
tree28d554b5e5539f76632699bcffe559445eae17d0 /format.go
initial import
Diffstat (limited to 'format.go')
-rw-r--r--format.go76
1 files changed, 76 insertions, 0 deletions
diff --git a/format.go b/format.go
new file mode 100644
index 0000000..77f5457
--- /dev/null
+++ b/format.go
@@ -0,0 +1,76 @@
+package float
+
+import (
+ "strconv"
+ "strings"
+)
+
+func split(s string, n int) (ret []string) {
+ var pos int
+ if rest := len(s) % n; rest > 0 {
+ ret = append(ret, s[:rest])
+ pos = rest
+ }
+ for pos < len(s) {
+ ret = append(ret, s[pos:pos+n])
+ pos += n
+ }
+ return ret
+}
+
+func fill(s string, n int) string {
+ if len(s) >= n {
+ return s[:n]
+ }
+ return s + strings.Repeat("0", n-len(s))
+}
+
+type Country struct {
+ Thousend, Decimal rune
+ Block, Fraction int
+}
+
+const (
+ Space = '\u0020'
+ Apostrophe = '\u0027'
+ Comma = '\u002c'
+ FullStop = '\u002e'
+ MiddleDot = '\u00b7'
+ ThinSpace = '\u2009'
+ NoBreakSpace = '\u202f'
+ DotAbove = '\u02d9'
+)
+
+var (
+ EN = Country{Space, FullStop, 3, 2} // SI EN
+ FR = Country{Space, Comma, 3, 2} // SI FR
+ US = Country{Comma, FullStop, 3, 2}
+ DE = Country{FullStop, Comma, 3, 2}
+ IR = Country{Space, MiddleDot, 3, 2}
+ CH = Country{Apostrophe, FullStop, 3, 2}
+ IT = Country{DotAbove, Comma, 3, 2}
+ CN = Country{Comma, FullStop, 4, 2}
+)
+
+func (c Country) Format(v float64) string {
+ s := strconv.FormatFloat(v, 'f', -1, 64)
+ neg := strings.HasPrefix(s, "-")
+ if neg {
+ s = s[1:]
+ }
+ parts := strings.Split(s, ".")
+ if len(parts) == 1 {
+ parts = append(parts, "")
+ }
+ lhs := split(parts[0], c.Block)
+ rhs := fill(parts[1], c.Fraction)
+ s = strings.Join(lhs, string(c.Thousend))
+ if neg {
+ s = "-" + s
+ }
+ return s + string(c.Decimal) + rhs
+}
+
+func Format(v float64) string {
+ return FR.Format(v)
+}