Skip to content

Commit

Permalink
Add Float#round method.
Browse files Browse the repository at this point in the history
  • Loading branch information
st0012 committed May 10, 2018
1 parent e57228b commit a452902
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
37 changes: 37 additions & 0 deletions vm/float.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,43 @@ func builtinFloatInstanceMethods() []*BuiltinMethodObject {
}
},
},
{
// Rounds float to a given precision in decimal digits (default 0 digits)
//
// ```Ruby
// 1.115.round # => 1
// 1.115.round(1) # => 1.1
// 1.115.round(2) # => 1.12
// -1.115.round # => -1
// -1.115.round(1) # => -1.1
// -1.115.round(2) # => -1.12
// ```
// @return [Integer]
Name: "round",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
var precision int

if len(args) > 1 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 0 or 1 argument. got=%v", strconv.Itoa(len(args)))
} else if len(args) == 1 {
int, ok := args[0].(*IntegerObject)

if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.IntegerClass, args[0].Class().Name)
}

precision = int.value
}


f := receiver.(*FloatObject).floatValue()
n := math.Pow10(precision)

return t.vm.initFloatObject(math.Round(f*n)/n)
}
},
},
{
// Returns true if Float is less than 0.0
//
Expand Down
24 changes: 24 additions & 0 deletions vm/float_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,30 @@ func TestFloatPositive(t *testing.T) {
}
}

func TestFloatRound(t *testing.T) {
tests := []struct {
input string
expected interface{}
}{
{"1.115.round", 1.0},
{"1.115.round(1)", 1.1},
{"1.115.round(2)", 1.12},
{"-1.115.round", -1.0},
{"-1.115.round(1)", -1.1},
{"-1.115.round(2)", -1.12},
{"1.115.round(-1)", 0.0},
{"-1.115.round(-1)", 0.0},
}

for i, tt := range tests {
v := initTestVM()
evaluated := v.testEval(t, tt.input, getFilename())
verifyExpected(t, i, evaluated, tt.expected)
v.checkCFP(t, i, 0)
v.checkSP(t, i, 1)
}
}

func TestFloatZero(t *testing.T) {
tests := []struct {
input string
Expand Down

0 comments on commit a452902

Please sign in to comment.