From ab52b887a34a9523019bf17113780acc5687a5bb Mon Sep 17 00:00:00 2001 From: Simon Etter Date: Mon, 6 Dec 2021 21:55:03 +0800 Subject: [PATCH] Allow underscores in big"[float]" (#43346) --- base/int.jl | 27 ++++++++++++++++----------- test/int.jl | 8 +++++++- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/base/int.jl b/base/int.jl index 953a4b15be3899..49ec0c54721f1d 100644 --- a/base/int.jl +++ b/base/int.jl @@ -689,25 +689,30 @@ julia> big"7891.5" ``` """ macro big_str(s) + message = "invalid number format $s for BigInt or BigFloat" + throw_error = :(throw(ArgumentError($message))) if '_' in s # remove _ in s[2:end-1] bf = IOBuffer(maxsize=lastindex(s)) - print(bf, s[1]) + c = s[1] + print(bf, c) + is_prev_underscore = (c == '_') + is_prev_dot = (c == '.') for c in SubString(s, 2, lastindex(s)-1) c != '_' && print(bf, c) + c == '_' && is_prev_dot && return throw_error + c == '.' && is_prev_underscore && return throw_error + is_prev_underscore = (c == '_') + is_prev_dot = (c == '.') end print(bf, s[end]) - seekstart(bf) - n = tryparse(BigInt, String(take!(bf))) - n === nothing || return n - else - n = tryparse(BigInt, s) - n === nothing || return n - n = tryparse(BigFloat, s) - n === nothing || return n + s = String(take!(bf)) end - message = "invalid number format $s for BigInt or BigFloat" - return :(throw(ArgumentError($message))) + n = tryparse(BigInt, s) + n === nothing || return n + n = tryparse(BigFloat, s) + n === nothing || return n + return throw_error end ## integer promotions ## diff --git a/test/int.jl b/test/int.jl index 52f554718645e1..b75337c405767b 100644 --- a/test/int.jl +++ b/test/int.jl @@ -324,10 +324,16 @@ end end end -@testset "issue #21092" begin +@testset "Underscores in big_str" begin @test big"1_0_0_0" == BigInt(1000) @test_throws ArgumentError big"1_0_0_0_" @test_throws ArgumentError big"_1_0_0_0" + + @test big"1_0.2_5" == BigFloat(10.25) + @test_throws ArgumentError big"_1_0.2_5" + @test_throws ArgumentError big"1_0.2_5_" + @test_throws ArgumentError big"1_0_.2_5" + @test_throws ArgumentError big"1_0._2_5" end # issue #26779