summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2017-05-21 19:03:36 +0200
committerDimitri Sokolyuk <demon@dim13.org>2017-05-21 19:03:36 +0200
commitc85c3bab7fc316293f284b5553ede4dd8c88b724 (patch)
treef3f826d440917cc0a4cceea2462a2d99a4bdf6b3
parent34f8f6b53230a91cfd98edd95f8297f93a6bb0b5 (diff)
Less convertion
-rw-r--r--format.go55
1 files changed, 27 insertions, 28 deletions
diff --git a/format.go b/format.go
index 644ec46..0758da8 100644
--- a/format.go
+++ b/format.go
@@ -27,30 +27,31 @@ func fill(s string, n int) string {
// Country settings
type Country struct {
- Thousend, Decimal rune // delimiter rune
- Block, Fraction int // block length
+ Thousend, Decimal, Neg string // delimiter
+ Block, Fraction int // length
}
const (
- Space = ' '
- Apostrophe = '\''
- Comma = ','
- FullStop = '.'
- MiddleDot = '\u00b7'
- ThinSpace = '\u2009'
- NoBreakSpace = '\u202f'
- DotAbove = '\u02d9'
+ Neg = "-"
+ Space = " "
+ Apostrophe = "'"
+ Comma = ","
+ FullStop = "."
+ 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} // 10000 based
+ EN = Country{Space, FullStop, Neg, 3, 2} // SI EN
+ FR = Country{Space, Comma, Neg, 3, 2} // SI FR
+ US = Country{Comma, FullStop, Neg, 3, 2}
+ DE = Country{FullStop, Comma, Neg, 3, 2}
+ IR = Country{Space, MiddleDot, Neg, 3, 2}
+ CH = Country{Apostrophe, FullStop, Neg, 3, 2}
+ IT = Country{DotAbove, Comma, Neg, 3, 2}
+ CN = Country{Comma, FullStop, Neg, 4, 2} // 10000 based
)
// DefaultFormat is europeian SI format
@@ -59,21 +60,19 @@ var DefaultFormat = FR
// Format float value as localized representation
func (c Country) Format(v float64) string {
s := strconv.FormatFloat(v, 'f', -1, 64)
- neg := strings.HasPrefix(s, "-")
+ neg := strings.HasPrefix(s, Neg)
if neg {
- s = s[1:]
- }
- parts := strings.Split(s, ".")
- if len(parts) == 1 {
- parts = append(parts, "")
+ s = s[1:] // stip neg
}
+ // add extra dot for there will be at least 2 parts
+ parts := strings.Split(s+FullStop, FullStop)
lhs := split(parts[0], c.Block)
- rhs := fill(parts[1], c.Fraction)
- s = strings.Join(lhs, string(c.Thousend))
+ s = strings.Join(lhs, c.Thousend)
if neg {
- s = "-" + s
+ s = c.Neg + s // rejoin neg
}
- return s + string(c.Decimal) + rhs
+ rhs := fill(parts[1], c.Fraction)
+ return s + c.Decimal + rhs
}
// Format float with default format