Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expression: function format incompatible #9182

Merged
merged 14 commits into from Jan 31, 2019
59 changes: 59 additions & 0 deletions expression/builtin_string.go
Expand Up @@ -2969,10 +2969,69 @@ func evalNumDecArgsForFormat(f builtinFunc, row chunk.Row) (string, string, bool
} else if d > formatMaxDecimals {
d = formatMaxDecimals
}
xStr, err = roundFormatArgs(xStr, int(d))
if err != nil {
return "", "", true, err
}
dStr := strconv.FormatInt(d, 10)
return xStr, dStr, false, nil
}

func roundFormatArgs(xStr string, maxNumDecimals int) (string, error) {
zz-jason marked this conversation as resolved.
Show resolved Hide resolved
if !strings.Contains(xStr, ".") {
return xStr, nil
}

eurekaka marked this conversation as resolved.
Show resolved Hide resolved
sign := false
// xStr cannot have '+' prefix now.
// It is built in `evalNumDecArgsFormat` after evaluating `Evalxxx` method.
if strings.HasPrefix(xStr, "-") {
xStr = strings.Trim(xStr, "-")
sign = true
}

xArr := strings.Split(xStr, ".")
integerPart := xArr[0]
decimalPart := xArr[1]

if len(decimalPart) > maxNumDecimals {
t := []byte(decimalPart)
carry := false
if t[maxNumDecimals] >= '5' {
carry = true
}
for i := maxNumDecimals - 1; i >= 0 && carry; i-- {
if t[i] == '9' {
t[i] = '0'
} else {
t[i] = t[i] + 1
carry = false
}
eurekaka marked this conversation as resolved.
Show resolved Hide resolved
}
decimalPart = string(t)
t = []byte(integerPart)
for i := len(integerPart) - 1; i >= 0 && carry; i-- {
if t[i] == '9' {
t[i] = '0'
} else {
t[i] = t[i] + 1
carry = false
}
}
if carry {
integerPart = "1" + string(t)
} else {
integerPart = string(t)
}
}

xStr = integerPart + "." + decimalPart
if sign {
xStr = "-" + xStr
}
return xStr, nil
}

type builtinFormatWithLocaleSig struct {
baseBuiltinFunc
}
Expand Down
7 changes: 7 additions & 0 deletions expression/builtin_string_test.go
Expand Up @@ -1608,6 +1608,13 @@ func (s *testEvaluatorSuite) TestFormat(c *C) {
ret interface{}
warnings int
}{
// issue #8796
{1.12345, 4, "1.1235", 0},
{9.99999, 4, "10.0000", 0},
{1.99999, 4, "2.0000", 0},
{1.09999, 4, "1.1000", 0},
{-2.5000, 0, "-3", 0},

{12332.123444, 4, "12,332.1234", 0},
{12332.123444, 0, "12,332", 0},
{12332.123444, -4, "12,332", 0},
Expand Down