My rough interpretation (which is by no means the official one, as I think
this is still up for debate), is as follows:,
1) convert(T,x) is the most specific: it will convert x to type T, throwing
an error if outside the range (though it can round, for instance when
converting to a Rational or FloatingPoint type). This can be called
implicitly, e.g. when assigning to a typed array.
2) T(x) does mostly the same thing, but is slightly more general
* when T : FloatingPoint, you can pass extra rounding arguments, e.g.
Float64(x,RoundDown)
* in some cases, x can be a string: at the moment this seems to only work
for BigFloat and BigInt, but perhaps this should apply to other types.
3) x % T is defined only for integer types: the idea is to be a module
conversion, and can be faster because no exceptions can be thrown.
Additionally, if x is a FloatingPoint type, then there are also the extra
methods round(T, x), trunc(T, x), floor(T, x), ceil(T, x) and the
non-exported Base.unsafe_trunc(T, x).
s
On Saturday, 21 March 2015 00:22:43 UTC+1, Milan Bouchet-Valat wrote:
Le vendredi 20 mars 2015 à 14:03 -0700, Julia User a écrit :
I looked through some of the Base source code and see different things
for conversions.
c%UInt8
convert(UInt8,x)
UInt8(t)
to name a few
Any official recommendation for someone starting out new - anything
which is planned to be depreciate soon.
I think all of them are OK, but the last one does not have the same
behavior:
julia UInt8(256)
ERROR: InexactError()
in call at base.jl:36
julia convert(UInt8, 256)
ERROR: InexactError()
in convert at int.jl:160
julia 256 % UInt8
0x00
The first one ends up calling the second one, so I'd say use it since
it's shorter. The last one does not check for overflow, so use it only
if you really want this behavior.
In short: in doubt, use the first one.
Regards