Skip to content

Commit fea0303

Browse files
committed
add bigdecimal
1 parent 16531b9 commit fea0303

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

spec/pg/numeric_spec.cr

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
require "../spec_helper"
22
require "../../src/pg_ext/big_rational"
3+
require "../../src/pg_ext/big_decimal"
34

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

13+
private def bd(d)
14+
BigDecimal.new(d)
15+
end
16+
1217
private def ex(which)
1318
case which
1419
when "nan"
@@ -82,6 +87,24 @@ describe PG::Numeric do
8287
end
8388
end
8489

90+
it "to_big_d" do
91+
[
92+
{"nan", bd(0)},
93+
{"0", bd(0)},
94+
{"0.0", bd(0)},
95+
{"1", bd(1)},
96+
{"-1", bd(-1)},
97+
{"1.30", bd(1.3)},
98+
{"12345.6789123", bd(12345.6789123)},
99+
{"-0.00009", bd(-0.00009)},
100+
{"-0.000009", bd(-0.000009)},
101+
{"-0.0000009", bd(-0.0000009)},
102+
{"-0.00000009", bd(-0.00000009)},
103+
].each do |x|
104+
ex(x[0]).to_big_d.should eq(x[1])
105+
end
106+
end
107+
85108
it "#to_s" do
86109
[
87110
{"nan", "NaN"},

src/pg_ext/big_decimal.cr

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
require "big"
2+
3+
module PG
4+
struct Numeric
5+
# Returns a BigDecimal representation of the numeric. This retains all precision.
6+
def to_big_d
7+
return BigDecimal.new("0") if nan? || ndigits == 0
8+
9+
# Since BigDecimal allows initialaztion from String, why should one reinvent the wheel?
10+
BigDecimal.new(to_s)
11+
end
12+
end
13+
14+
class ResultSet
15+
def read(t : BigDecimal.class)
16+
read(PG::Numeric).to_big_d
17+
end
18+
19+
def read(t : BigDecimal?.class)
20+
read(PG::Numeric?).try &.to_big_d
21+
end
22+
end
23+
end

0 commit comments

Comments
 (0)