mirror of
https://github.com/robertkrimen/otto
synced 2025-10-12 20:27:30 +08:00
Fix Number.prototype.toFixed to use ToString if exponent >= 21
This commit is contained in:
parent
e2ebc15faf
commit
46f720d27b
|
@ -1,6 +1,7 @@
|
|||
package otto
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
|
@ -44,12 +45,16 @@ func builtinNumber_valueOf(call FunctionCall) Value {
|
|||
}
|
||||
|
||||
func builtinNumber_toFixed(call FunctionCall) Value {
|
||||
precision := toIntegerFloat(call.Argument(0))
|
||||
if 20 < precision || 0 > precision {
|
||||
panic(newRangeError("toFixed() precision must be between 0 and 20"))
|
||||
}
|
||||
if call.This.IsNaN() {
|
||||
return toValue_string("NaN")
|
||||
}
|
||||
precision := toIntegerFloat(call.Argument(0))
|
||||
if 0 > precision {
|
||||
panic(newRangeError("RangeError: toFixed() precision must be greater than 0"))
|
||||
value := toFloat(call.This)
|
||||
if math.Abs(value) >= 1e21 {
|
||||
return toValue_string(floatToString(value, 64))
|
||||
}
|
||||
return toValue_string(strconv.FormatFloat(toFloat(call.This), 'f', int(precision), 64))
|
||||
}
|
||||
|
|
|
@ -79,6 +79,29 @@ func TestNumber_toFixed(t *testing.T) {
|
|||
test(`2.34.toFixed(1)`, "2.3")
|
||||
test(`-2.34.toFixed(1)`, "-2.3")
|
||||
test(`(-2.34).toFixed(1)`, "-2.3")
|
||||
|
||||
test(`raise:
|
||||
new Number("a").toFixed(Number.POSITIVE_INFINITY);
|
||||
`, "RangeError: toFixed() precision must be between 0 and 20")
|
||||
|
||||
test(`
|
||||
[
|
||||
new Number(1e21).toFixed(),
|
||||
new Number(1e21).toFixed(0),
|
||||
new Number(1e21).toFixed(1),
|
||||
new Number(1e21).toFixed(1.1),
|
||||
new Number(1e21).toFixed(0.9),
|
||||
new Number(1e21).toFixed("1"),
|
||||
new Number(1e21).toFixed("1.1"),
|
||||
new Number(1e21).toFixed("0.9"),
|
||||
new Number(1e21).toFixed(Number.NaN),
|
||||
new Number(1e21).toFixed("some string")
|
||||
];
|
||||
`, "1e+21,1e+21,1e+21,1e+21,1e+21,1e+21,1e+21,1e+21,1e+21,1e+21")
|
||||
|
||||
test(`raise:
|
||||
new Number(1e21).toFixed(Number.POSITIVE_INFINITY);
|
||||
`, "RangeError: toFixed() precision must be between 0 and 20")
|
||||
}
|
||||
|
||||
func TestNumber_toExponential(t *testing.T) {
|
||||
|
|
|
@ -8,7 +8,7 @@ import (
|
|||
"unicode/utf16"
|
||||
)
|
||||
|
||||
var matchLeading0Exponent = regexp.MustCompile(`([eE][\+\-])0+([1-9])`)
|
||||
var matchLeading0Exponent = regexp.MustCompile(`([eE][\+\-])0+([1-9])`) // 1e-07 => 1e-7
|
||||
|
||||
func floatToString(value float64, bitsize int) string {
|
||||
// TODO Fit to ECMA-262 9.8.1 specification
|
||||
|
|
Loading…
Reference in New Issue
Block a user