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
63 changes: 63 additions & 0 deletions expression/builtin_string.go
Expand Up @@ -2970,9 +2970,72 @@ func evalNumDecArgsForFormat(f builtinFunc, row chunk.Row) (string, string, bool
d = formatMaxDecimals
}
dStr := strconv.FormatInt(d, 10)
xStr, err = roundFormatArgs(xStr, dStr)
if err != nil {
return "", "", isNull, err
zz-jason marked this conversation as resolved.
Show resolved Hide resolved
}
return xStr, dStr, false, nil
}

func roundFormatArgs(xStr, dStr string) (string, error) {
zz-jason marked this conversation as resolved.
Show resolved Hide resolved
if strings.Contains(xStr, ".") {
zz-jason 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, "-") {
eurekaka marked this conversation as resolved.
Show resolved Hide resolved
xStr = strings.Trim(xStr, "-")
sign = true
}
if strings.HasPrefix(xStr, "+") {
zz-jason marked this conversation as resolved.
Show resolved Hide resolved
return "", errors.Errorf("xStr can not has `+` prefix")
}

xArr := strings.Split(xStr, ".")
x1 := xArr[0]
x2 := xArr[1]
zz-jason marked this conversation as resolved.
Show resolved Hide resolved
digit, err := strconv.Atoi(dStr)
if err != nil {
return "", err
}
if len(x2) > digit {
t := []byte(x2)
carry := false
if t[digit] >= '5' {
carry = true
}
for i := digit - 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
}
x2 = string(t)
t = []byte(x1)
for i := len(x1) - 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
if carry {
x1 = "1" + string(t)
} else {
x1 = string(t)
}
}

xStr = x1 + "." + x2
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