Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a value with a other values type

Tags:

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)
like image 926
loose11 Avatar asked Nov 18 '16 14:11

loose11


People also ask

What is datatype casting?

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.

Which of the following is the example of the type casting?

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.

What does type cast mean in Python?

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.

Can you cast variables in Python?

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.


1 Answers

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.

like image 173
brianpck Avatar answered Sep 26 '22 16:09

brianpck