diff --git a/builtin_number.go b/builtin_number.go index 6996a8e7..202a81cb 100644 --- a/builtin_number.go +++ b/builtin_number.go @@ -3,6 +3,10 @@ package otto import ( "math" "strconv" + + "golang.org/x/text/language" + "golang.org/x/text/message" + "golang.org/x/text/number" ) // Number @@ -96,5 +100,13 @@ func builtinNumber_isNaN(call FunctionCall) Value { } func builtinNumber_toLocaleString(call FunctionCall) Value { - return builtinNumber_toString(call) + value := call.thisClassObject(classNumber).primitiveValue() + locale := call.Argument(0) + lang := defaultLanguage + if locale.IsDefined() { + lang = language.MustParse(locale.string()) + } + + p := message.NewPrinter(lang) + return toValue_string(p.Sprintf("%v", number.Decimal(value.value))) } diff --git a/go.mod b/go.mod index c29ec963..5c132b43 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.18 require ( github.com/stretchr/testify v1.8.1 + golang.org/x/text v0.4.0 gopkg.in/readline.v1 v1.0.0-20160726135117-62c6fe619375 gopkg.in/sourcemap.v1 v1.0.5 ) diff --git a/go.sum b/go.sum index 7580fb36..67a9e023 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/readline.v1 v1.0.0-20160726135117-62c6fe619375 h1:hPki/oSSWOLiI9Gc9jyIoj33O3j29fUc9PlLha2yDj0= diff --git a/issue_test.go b/issue_test.go index 783dedcc..41c9427a 100644 --- a/issue_test.go +++ b/issue_test.go @@ -1122,3 +1122,12 @@ func Test_issue177(t *testing.T) { require.NoError(t, err) require.Equal(t, float64(9), exp) } + +func Test_issue285(t *testing.T) { + vm := New() + val, err := vm.Run(`(1451).toLocaleString('en-US')`) + require.NoError(t, err) + exp, err := val.Export() + require.NoError(t, err) + require.Equal(t, "1,451", exp) +} diff --git a/locale.go b/locale.go new file mode 100644 index 00000000..e16aa5df --- /dev/null +++ b/locale.go @@ -0,0 +1,7 @@ +package otto + +import "golang.org/x/text/language" + +var ( + defaultLanguage = language.MustParse("en-US") +)