Skip to content

Commit e54c38d

Browse files
committed
Merge pull request #13376 from JuliaLang/sb/bigint-trunc
add trunc methods to BigInt, fixes #13367
2 parents 4c7f220 + b31925c commit e54c38d

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

base/gmp.jl

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import Base: *, +, -, /, <, <<, >>, >>>, <=, ==, >, >=, ^, (~), (&), (|), ($),
88
binomial, cmp, convert, div, divrem, factorial, fld, gcd, gcdx, lcm, mod,
99
ndigits, promote_rule, rem, show, isqrt, string, isprime, powermod,
1010
sum, trailing_zeros, trailing_ones, count_ones, base, tryparse_internal,
11-
bin, oct, dec, hex, isequal, invmod, prevpow2, nextpow2, ndigits0z, widen, signed
11+
bin, oct, dec, hex, isequal, invmod, prevpow2, nextpow2, ndigits0z, widen, signed, unsafe_trunc, trunc
1212

1313
if Clong == Int32
1414
typealias ClongMax Union{Int8, Int16, Int32}
@@ -120,13 +120,23 @@ end
120120

121121
convert(::Type{BigInt}, x::Bool) = BigInt(UInt(x))
122122

123-
function convert(::Type{BigInt}, x::Float64)
124-
!isinteger(x) && throw(InexactError())
123+
124+
function unsafe_trunc(::Type{BigInt}, x::CdoubleMax)
125125
z = BigInt()
126126
ccall((:__gmpz_set_d, :libgmp), Void, (Ptr{BigInt}, Cdouble), &z, x)
127127
return z
128128
end
129129

130+
function convert(::Type{BigInt}, x::CdoubleMax)
131+
isinteger(x) || throw(InexactError())
132+
unsafe_trunc(BigInt,x)
133+
end
134+
135+
function trunc(::Type{BigInt}, x::CdoubleMax)
136+
isfinite(x) || throw(InexactError())
137+
unsafe_trunc(BigInt,x)
138+
end
139+
130140
convert(::Type{BigInt}, x::Float16) = BigInt(Float64(x))
131141
convert(::Type{BigInt}, x::Float32) = BigInt(Float64(x))
132142

test/bigint.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,3 +280,19 @@ ndigits_mismatch(n) = ndigits(n) != ndigits(BigInt(n))
280280
@test BigInt(2.0) == BigInt(2.0f0) == BigInt(big(2.0)) == 2
281281
@test_throws InexactError convert(BigInt, 2.1)
282282
@test_throws InexactError convert(BigInt, big(2.1))
283+
284+
# issue #13367
285+
@test trunc(BigInt,2.1) == 2
286+
@test round(BigInt,2.1) == 2
287+
@test floor(BigInt,2.1) == 2
288+
@test ceil(BigInt,2.1) == 3
289+
290+
@test trunc(BigInt,2.1f0) == 2
291+
@test round(BigInt,2.1f0) == 2
292+
@test floor(BigInt,2.1f0) == 2
293+
@test ceil(BigInt,2.1f0) == 3
294+
295+
@test_throws InexactError trunc(BigInt,Inf)
296+
@test_throws InexactError round(BigInt,Inf)
297+
@test_throws InexactError floor(BigInt,Inf)
298+
@test_throws InexactError ceil(BigInt,Inf)

0 commit comments

Comments
 (0)