Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't parse transform float string into int?

Tags:

julia

When I try to use parse this way: parse(Int64, "3.1459"), I get an error, because '.' is an invalid base 10 digit. I know the error gets raised because of the period, but is there any particular reason why Julia couldn't convert a float string to a integer like this? Any other way to do it?


2 Answers

Well, it isn't an integer so it isn't really clear what it should return. You could just parse it as a float and then round it as you want, e.g:


julia> v = parse(Float64, "3.1459")
3.1459

julia> trunc(Int, v)
3

julia> ceil(Int, v)
4

julia> round(Int, v)
3
like image 131
Kristoffer Carlsson Avatar answered Aug 18 '26 13:08

Kristoffer Carlsson


I'm not sure the error gets raised because of the period - rather because you can parse a decimal into an integer without specifying how you want to round:


julia> parse(Float64, "3.14159")
3.14159

julia> Int(round(parse(Float64, "3.14159")))
3
like image 45
Nils Gudat Avatar answered Aug 18 '26 14:08

Nils Gudat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!