Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add bigdecimal #132

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions spec/pg/numeric_spec.cr
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require "../spec_helper"
require "../../src/pg_ext/big_rational"
require "../../src/pg_ext/big_decimal"

private def n(nd, w, s, ds, d)
PG::Numeric.new(nd.to_i16, w.to_i16, s.to_i16, ds.to_i16, d.map(&.to_i16))
Expand All @@ -9,6 +10,10 @@ private def br(n, d)
BigRational.new(n, d)
end

private def bd(d)
BigDecimal.new(d)
end

private def ex(which)
case which
when "nan"
Expand Down Expand Up @@ -100,6 +105,24 @@ describe PG::Numeric do
end
end

it "to_big_d" do
[
{"nan", bd(0)},
{"0", bd(0)},
{"0.0", bd(0)},
{"1", bd(1)},
{"-1", bd(-1)},
{"1.30", bd(1.3)},
{"12345.6789123", bd(12345.6789123)},
{"-0.00009", bd(-0.00009)},
{"-0.000009", bd(-0.000009)},
{"-0.0000009", bd(-0.0000009)},
{"-0.00000009", bd(-0.00000009)},
].each do |x|
ex(x[0]).to_big_d.should eq(x[1])
end
end

it "#to_s" do
[
{"nan", "NaN"},
Expand Down
21 changes: 21 additions & 0 deletions src/pg_ext/big_decimal.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require "big"

module PG
struct Numeric
# Returns a BigDecimal representation of the numeric. This retains all precision.
def to_big_d
return BigDecimal.new(0) if nan? || ndigits == 0
BigDecimal.new(to_s)
greenbigfrog marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is pg/pg_ext/big_rational so this method can become:

def to_big_d : BigDecimal
  to_big_r.to_big_d
end

In fact, maybe both files could be merged into a single pg/pg_ext/big file?

end
end

class ResultSet
def read(t : BigDecimal.class)
read(PG::Numeric).to_big_d
end

def read(t : BigDecimal?.class)
read(PG::Numeric?).try &.to_big_d
greenbigfrog marked this conversation as resolved.
Show resolved Hide resolved
end
end
end