diff --git a/numbers.go b/numbers.go index ecc4ece..f3aa3e6 100644 --- a/numbers.go +++ b/numbers.go @@ -43,19 +43,30 @@ func FormatDecimal(f float64) string { // FormatDecimalN formats a float with N decimal places. func FormatDecimalN(f float64, decimals int) string { nf := getNumberFormat() - intPart := int64(f) - fracPart := math.Abs(f - float64(intPart)) + negative := f < 0 + absVal := math.Abs(f) + intPart := int64(absVal) + fracPart := absVal - float64(intPart) intStr := formatIntWithSep(intPart, nf.ThousandsSep) if decimals <= 0 || fracPart == 0 { + if negative { + return "-" + intStr + } return intStr } multiplier := math.Pow(10, float64(decimals)) fracInt := int64(math.Round(fracPart * multiplier)) if fracInt == 0 { + if negative { + return "-" + intStr + } return intStr } fracStr := core.Sprintf("%0*d", decimals, fracInt) fracStr = trimRight(fracStr, "0") + if negative { + return "-" + intStr + nf.DecimalSep + fracStr + } return intStr + nf.DecimalSep + fracStr } diff --git a/numbers_test.go b/numbers_test.go index 235b5b0..df4d59b 100644 --- a/numbers_test.go +++ b/numbers_test.go @@ -46,6 +46,8 @@ func TestFormatDecimal(t *testing.T) { {1.0, "1"}, {1234.56, "1,234.56"}, {0.1, "0.1"}, + {-0.1, "-0.1"}, + {-1234.56, "-1,234.56"}, } for _, tt := range tests { @@ -71,6 +73,7 @@ func TestFormatPercent(t *testing.T) { {1.0, "100%"}, {0.0, "0%"}, {0.333, "33.3%"}, + {-0.1, "-10%"}, } for _, tt := range tests { @@ -164,4 +167,7 @@ func TestFormatNumberFromLocale(t *testing.T) { if got := FormatPercent(0.85); got != "85 %" { t.Errorf("FormatPercent(fr) = %q, want %q", got, "85 %") } + if got := FormatDecimal(-0.1); got != "-0,1" { + t.Errorf("FormatDecimal(fr, negative) = %q, want %q", got, "-0,1") + } }