# [Help] Converting floats into integer

• (2 Pages)
• 1
• 2

## 15 Replies - 1503 Views - Last Post: 02 December 2012 - 10:15 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=301642&amp;s=998c9c24207884d6abede5c1723484cd&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 chan 06

Reputation: 2
• Posts: 63
• Joined: 07-October 12

# [Help] Converting floats into integer

Posted 26 November 2012 - 08:07 AM

Well, I wondering if there is a way that if a user enters an integer it won't automatically convert to a float.

So, if user inputs:

num1 = 2.0
num2 = 1.0

I wonder, if there is a way where I could determine if is a whole number?

```def division(num1, num2):

while(True):
try:
num1 = float(input("Enter a value for denominator."))
num2 = float(input("Enter a value for numerator."))
break
except ValueError:
print ("Oops! That was not a valid number.")
except ZeroDivisionerror:
print ("Oops! You cannot divide by zero.")
```

Is This A Good Question/Topic? 0

## Replies To: [Help] Converting floats into integer

### #2 tlhIn`toq

Reputation: 5871
• Posts: 12,798
• Joined: 02-June 10

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 08:51 AM

Python is not my language but... Doesn't this line say you WANT to cast the input to a float?

07 num1 = float(input("Enter a value for denominator."))

Knowing nothing about this language my first experiment would be to replace float with int (integer) to see what happens.

### #3 chan 06

Reputation: 2
• Posts: 63
• Joined: 07-October 12

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 08:58 AM

No. I mean, if user enters an integer, it will basically convert into float. What I want to do is, if user enters an integer value, the answer will be stored in integer value.

```x, y = 2, 1
print x/y # Restores the result as an integer.
```

### #4 tlhIn`toq

Reputation: 5871
• Posts: 12,798
• Joined: 02-June 10

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 09:08 AM

I guess this is a good example of why not to answer questions outside of one's normal language. In any other language (give or take the exact syntax of parenthesis etc.) this looks like you are deliberatly casting the input to a float

float(input("Enter a value for denominator."))

then assigning that float to num1

num1 = float(input("Enter a value for denominator."))

UPDATE: I don't think I'm too far off in my thinking. This tutorial:
http://mail.python.o...ary/003494.html

Says the same thing:

Quote

Another way is this:

selection = int(raw_input('Enter number: '))

which is nicer if you want to always think of selection as a number.

This post has been edited by tlhIn`toq: 26 November 2012 - 09:10 AM

### #5 Python_4_President

• D.I.C Regular

Reputation: 53
• Posts: 321
• Joined: 13-August 11

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 09:45 AM

You can check with isdigit. See the code below for example usage.

| isdigit(...)
| S.isdigit() -> bool
|
| Return True if all characters in S are digits
| and there is at least one character in S, False otherwise.

```def division(num1, num2):

def getTypedValue(entry):
#strings have method isdigit which returns True if the string consists of digits (Integers) and false otherwise
if entry.isdigit():
return int(entry)
return float(entry)

while(True):
try:
num1 = getTypedValue(input("Enter a value for denominator."))
num2 = getTypedValue(input("Enter a value for numerator."))

if num1 and num2:
break
except ValueError:
print ("Oops! That was not a valid number.")
except ZeroDivisionerror:
print ("Oops! You cannot divide by zero.")

```

This post has been edited by Python_4_President: 26 November 2012 - 09:46 AM

### #6 jon.kiparsky

• Pancakes!

Reputation: 8443
• Posts: 14,566
• Joined: 19-March 11

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 12:31 PM

isdigit is misleadingly named, since 1234 is not a digit*, but "1234".isdigit() returns true. However, it does behave as described above, and is probably the easiest test you can perform on a string to decide whether to convert it to an int value.

However, isdigit will give you a false for a number with a decimal point, so this will result in a float if the user enters "1.000", which is not what you want. To test for this, you could do this:

```inputstring = float(inputstring)  # assuming you've got your input string already
if int(inputstring) == inputstring:
inputstring= int(inputstring)

```

This will obviate the need for the isdigit check.

But why do you want to do this? This seems guaranteed to cause weird bugs later on.

*okay, in base 1235 it is a digit, you got me... />

This post has been edited by jon.kiparsky: 26 November 2012 - 12:32 PM

### #7 sepp2k

• D.I.C Lover

Reputation: 2201
• Posts: 3,397
• Joined: 21-June 11

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 12:37 PM

jon.kiparsky, on 26 November 2012 - 08:31 PM, said:

However, isdigit will give you a false for a number with a decimal point

And for negative numbers, too.

### #8 chan 06

Reputation: 2
• Posts: 63
• Joined: 07-October 12

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 09:24 PM

Python_4_President, on 26 November 2012 - 09:45 AM, said:

You can check with isdigit. See the code below for example usage.

| isdigit(...)
| S.isdigit() -> bool
|
| Return True if all characters in S are digits
| and there is at least one character in S, False otherwise.

```def division(num1, num2):

def getTypedValue(entry):
#strings have method isdigit which returns True if the string consists of digits (Integers) and false otherwise
if entry.isdigit():
return int(entry)
return float(entry)

while(True):
try:
num1 = getTypedValue(input("Enter a value for denominator."))
num2 = getTypedValue(input("Enter a value for numerator."))

if num1 and num2:
break
except ValueError:
print ("Oops! That was not a valid number.")
except ZeroDivisionerror:
print ("Oops! You cannot divide by zero.")

```

Thank you Python_4_President, what if the user enters a negative value? How would I be able to convert to whole number?

### #9 tlhIn`toq

Reputation: 5871
• Posts: 12,798
• Joined: 02-June 10

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 11:14 PM

jon.kiparsky, on 26 November 2012 - 01:31 PM, said:

```inputstring = float(inputstring)  # assuming you've got your input string already
if int(inputstring) == inputstring:
inputstring= int(inputstring)

```

Is there any reason you have to do the if check? Couldn't this be abbreviated to just
```  inputstring= int(inputstring)
```

If inputstring is already an int then no harm no foul, right?

### #10 jon.kiparsky

• Pancakes!

Reputation: 8443
• Posts: 14,566
• Joined: 19-March 11

## Re: [Help] Converting floats into integer

Posted 26 November 2012 - 11:22 PM

Well, as I undersatnd it, the number should be returned as a float if a float is needed to represent a fractional part, or as an int if there is no fractional part to represent.
I may be wrong, but that's how I read the original query, so that's what this does.
If there's actually no wish for the fractional part - if "5.412" should be truncated to 5, that is - then yes, you're exactly right.

### #11 Blecha

Reputation: 5
• Posts: 16
• Joined: 28-November 12

## Re: [Help] Converting floats into integer

Posted 28 November 2012 - 09:27 PM

You could do an if statement with some regex on the string before casting it to an int or float. Something like:
```string = raw_input()
if re.match("[0-9]\.\d+[1-9]", string):
try:
number = float(string)
except:
print "Thats not a number"

```

### #12 Blecha

Reputation: 5
• Posts: 16
• Joined: 28-November 12

## Re: [Help] Converting floats into integer

Posted 28 November 2012 - 09:37 PM

This also won't work for negatives but you could filter for that and then strip the minus before proceeding and multiplying the result by -1.0 if it was a negative.

### #13 Blecha

Reputation: 5
• Posts: 16
• Joined: 28-November 12

## Re: [Help] Converting floats into integer

Posted 28 November 2012 - 09:52 PM

Also, I just realized the previous regex will be false for 1.1 so I fixed it by doing:
```string = raw_input()
if re.match("[0-9]\..*[1-9]", string):
try:
number = float(string)
except:
print "Thats not a number"
else:
try:
number = int(string)
except:
print "Thats not a number"

```

if int(inputstring) == inputstring: probably is still the best way but Ive been itching to use some regex.
PS I really hope I unlock the ability to edit soon

### #14 Python_4_President

• D.I.C Regular

Reputation: 53
• Posts: 321
• Joined: 13-August 11

## Re: [Help] Converting floats into integer

Posted 28 November 2012 - 09:57 PM

Negative/positive float pattern fix
```"^-?\d+\.\d+\$"
```

```>>> pat = "^-?\d+\.\d+\$"
>>> re.search(pat, "15")
>>> re.search(pat, "-15")
>>> re.search(pat, "-1.5")
<_sre.SRE_Match object at 0x7f9b1875f100>
>>> re.search(pat, "1.5")
<_sre.SRE_Match object at 0x7f9b1875f168>
>>> re.search(pat, "Hello world! 1.5")
>>> re.search(pat, "Hello world! -1.5")
>>> re.search(pat, "     -1.5")
>>> re.search(pat, "-1.5    ")
>>> re.search(pat, "-1.5HelloWorld!")
>>> re.search(pat, "-1.5HelloWorld!1.5")
>>> re.search(pat, "-1.5HelloWorld!-1.5")
>>> re.search(pat, "-1.5")
<_sre.SRE_Match object at 0x7f9b1875f100>

```

Also, in case I forgot what the original requirements were, here's an ANTI-negative pattern.

```"^\d+\.\d+\$"
```

I think the general consensus about regular expressions is that they're inaccessible to newbies.

I love them, though. Maybe I should do a regex tutorial...

Hmm... Does it help if I translate from Regular Expression to English?

"^-?\d+\.\d+\$" -> Line starting with (maybe) a minus sign followed by one or more somethings in the class of digits followed by a . followed by one or more somethings in the class of digits followed by the end of the line?

What if I mix regex with English?

"^-?\d+\.\d+\$" -> Line starting with ('^') maybe ('?') a minus sign ('-') followed by one or more ('+') somethings in the class of digits ('\d') followed by a . ('\.') followed by one or more ('+') somethings in the class of digits ('\d') followed by the end of the line ('\$')?

Now that I look at it, though.. I often leave off a leading zero when only entering the fractional part. (".5", ".8", etc)

My pattern won't match that, but this one will:
```"^-?\d*\.\d+\$"

```

This post has been edited by Python_4_President: 29 November 2012 - 09:47 AM

### #15 npanagakis

Reputation: 1
• Posts: 23
• Joined: 01-December 12

## Re: [Help] Converting floats into integer

Posted 02 December 2012 - 09:46 PM

These guys have nice ideas, and another one to consider is this:
```num = input()
num1 = float(num)

```

Just a guess. Hope it helps (: