diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2021-08-23 10:44:04 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2021-08-23 10:53:23 +0900 |
| commit | 6f46f8887334d99fb2ccec7688f99c8bda080408 (patch) | |
| tree | d31d1640c199d12edd03e70c00f8aac78b91aa05 | |
| parent | 11cfe77eb1675d461709bda4e413ee2966945195 (diff) | |
| download | mruby-6f46f8887334d99fb2ccec7688f99c8bda080408.tar.gz mruby-6f46f8887334d99fb2ccec7688f99c8bda080408.zip | |
numeric.c: fix: `-0.0.abs` returned `-0.0`.
| -rw-r--r-- | src/numeric.c | 10 | ||||
| -rw-r--r-- | test/t/float.rb | 12 |
2 files changed, 22 insertions, 0 deletions
diff --git a/src/numeric.c b/src/numeric.c index c159c717a..1a006b7e3 100644 --- a/src/numeric.c +++ b/src/numeric.c @@ -978,6 +978,15 @@ flo_nan_p(mrb_state *mrb, mrb_value num) { return mrb_bool_value(isnan(mrb_float(num))); } + +static mrb_value +flo_abs(mrb_state *mrb, mrb_value num) +{ + mrb_float f = mrb_float(num); + + if (signbit(f)) return mrb_float_value(mrb, -f); + return num; +} #endif /* @@ -1910,6 +1919,7 @@ mrb_init_numeric(mrb_state *mrb) mrb_define_method(mrb, fl, "to_s", flo_to_s, MRB_ARGS_NONE()); /* 15.2.9.3.16(x) */ mrb_define_method(mrb, fl, "inspect", flo_to_s, MRB_ARGS_NONE()); mrb_define_method(mrb, fl, "nan?", flo_nan_p, MRB_ARGS_NONE()); + mrb_define_method(mrb, fl, "abs", flo_abs, MRB_ARGS_NONE()); /* 15.2.7.4.3 */ #ifdef INFINITY mrb_define_const_id(mrb, fl, MRB_SYM(INFINITY), mrb_float_value(mrb, INFINITY)); diff --git a/test/t/float.rb b/test/t/float.rb index a76dbf39b..e4c25b34e 100644 --- a/test/t/float.rb +++ b/test/t/float.rb @@ -303,4 +303,16 @@ assert('Float#eql?') do assert_not_operator(5.0, :eql?, "5.0") end +assert('Float#abs') do + f = 1.0 + assert_equal(1.0, f.abs) + f = -1.0 + assert_equal(1.0, f.abs) + f = 0.0 + assert_equal(0.0, f.abs) + # abs(negative zero) should be positive zero + f = -0.0 + assert_equal(0.0, f.abs) +end + end # const_defined?(:Float) |
