Last active
August 3, 2022 13:55
-
-
Save henrik/a28dd7c796355deac29ec5c7dd2dd152 to your computer and use it in GitHub Desktop.
BigDecimal.with_decimal_precision
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BigDecimal | |
# `BigDecimal(123.456, 2)` becomes 120.0. It keeps 2 *significant digits*. | |
# If you want two *decimals* of precision, use this method. | |
def self.with_decimal_precision(value, precision) | |
if value.is_a?(Float) | |
length_before_decimal = Math.log10(value.abs).to_i + 1 # log for performance. | |
BigDecimal(value, length_before_decimal + precision) | |
else | |
BigDecimal(value, precision) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rails_helper" | |
RSpec.describe BigDecimal do | |
describe ".with_decimal_precision" do | |
it "turns a float into a BigDecimal with the given decimal precision" do | |
expect(BigDecimal.with_decimal_precision(1234.5678, 0)).to eq(BigDecimal("1235")) | |
expect(BigDecimal.with_decimal_precision(1234.5678, 1)).to eq(BigDecimal("1234.6")) | |
expect(BigDecimal.with_decimal_precision(1234.5678, 2)).to eq(BigDecimal("1234.57")) | |
expect(BigDecimal.with_decimal_precision(1234.5678, 5)).to eq(BigDecimal("1234.56780")) | |
end | |
it "handles negative floats" do | |
expect(BigDecimal.with_decimal_precision(-1234.5678, 2)).to eq(BigDecimal("-1234.57")) | |
end | |
it "handles negative precisions" do | |
expect(BigDecimal.with_decimal_precision(1234.5678, -1)).to eq(BigDecimal("1230")) | |
expect(BigDecimal.with_decimal_precision(1234.5678, -2)).to eq(BigDecimal("1200")) | |
end | |
it "turns non-floats into BigDecimal, ignoring the precision" do | |
expect(BigDecimal.with_decimal_precision(1234, 2)).to eq(BigDecimal("1234")) | |
expect(BigDecimal.with_decimal_precision("1234.567", 2)).to eq(BigDecimal("1234.567")) | |
expect(BigDecimal.with_decimal_precision(BigDecimal("1234.567"), 2)).to eq(BigDecimal("1234.567")) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment