From c85c3bab7fc316293f284b5553ede4dd8c88b724 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Sun, 21 May 2017 19:03:36 +0200 Subject: Less convertion --- format.go | 55 +++++++++++++++++++++++++++---------------------------- 1 file 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 -- cgit v1.2.3