Skip to content

Commit

Permalink
Add BigDecimal.with_rounding_mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Jul 7, 2020
1 parent aa816a4 commit 96b9ef9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
8 changes: 8 additions & 0 deletions spec/std/big/big_decimal_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,14 @@ describe BigDecimal do
end
end

describe ".with_rounding_mode" do
it "sets given mode as .rounding_mode within yielded block" do
BigDecimal.with_rounding_mode(:half_even) do
BigDecimal.rounding_mode.should eq(BigDecimal::RoundingMode::HALF_EVEN)
end
end
end

it "performs arithmetic with other number types" do
(1.to_big_d + 2).should eq(BigDecimal.new("3.0"))
(2 + 1.to_big_d).should eq(BigDecimal.new("3.0"))
Expand Down
22 changes: 22 additions & 0 deletions src/big/big_decimal.cr
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,28 @@ struct BigDecimal < Number
end
end

# Executes the provided block, preserving the rounding mode; *mode* argument
# is set as `BigDecimal.rounding_mode` inside the block.
#
# ```
# BigDecimal.rounding_mode = :half_even
#
# # *mode* argument is set as `BigDecimal.rounding_mode` inside the block
# BigDecimal.with_rounding_mode(:up) do
# BigDecimal.rounding_mode # => BigDecimal::RoundingMode::UP
# end
#
# BigDecimal.rounding_mode # => BigDecimal::RoundingMode::HALF_EVEN
# ```
#
# NOTE: Uses `save_rounding_mode` internally.
def self.with_rounding_mode(mode : RoundingMode?)
save_rounding_mode do
@@rounding_mode = mode
yield
end
end

# Rounds to the nearest integer (by default), returning the result as a `BigDecimal`.
#
# ```
Expand Down

0 comments on commit 96b9ef9

Please sign in to comment.