Is it possible to cast a number behalf of a other number? I tried this one, but type returns a string.
n = 1.34
i = 10
type(i)(n)
A data type that can be changed to another data type is castable from the source data type to the target data type. The casting of one data type to another can occur implicitly or explicitly. The cast functions or CAST specification (see CAST specification) can be used to explicitly change a data type.
An example of typecasting is converting an integer to a string. This might be done in order to compare two numbers, when one number is saved as a string and the other is an integer. For example, a mail program might compare the first part of a street address with an integer.
Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users.
There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.
As mentioned, your example works fine:
>>> from decimal import Decimal
>>> a = 5
>>> b = 5.0
>>> c = Decimal(5)
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>> type(c)
<class 'decimal.Decimal'>
Cast b (float) as a's type (int):
>>> type(a)(b)
5
Cast a (int) as b type (float):
>>> type(b)(a)
5.0
Cast a (int) as c type (Decimal):
>>> type(c)(a)
Decimal('5')
Note that Python's duck-typing often makes this kind of casting unnecessary, though I can imagine some scenarios where it would be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With