[Help] Converting floats into integer

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 1256 Views - Last Post: 02 December 2012 - 10:15 PM Rate Topic: -----

#1 chan 06  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • 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
answer = 1.0

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

def division(num1, num2):
    answer = num1/num2
    return answer

while(True):
    try:
        num1 = float(input("Enter a value for denominator."))
        num2 = float(input("Enter a value for numerator."))
        answer = division(num1, num2)
        print(num1, "/", num2, "=", answer)
        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  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5441
  • View blog
  • Posts: 11,673
  • 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.
Was This Post Helpful? 0
  • +
  • -

#3 chan 06  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • 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.

Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5441
  • View blog
  • Posts: 11,673
  • 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

Was This Post Helpful? 1
  • +
  • -

#5 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • 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.

see help(str) for more info.

| 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):
    answer = num1/num2
    return answer


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:
            answer = division(num1, num2)
            print(num1, "/", num2, "=", answer)
            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

Was This Post Helpful? 3
  • +
  • -

#6 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7578
  • View blog
  • Posts: 12,742
  • 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

Was This Post Helpful? 4
  • +
  • -

#7 sepp2k  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2091
  • View blog
  • Posts: 3,185
  • Joined: 21-June 11

Re: [Help] Converting floats into integer

Posted 26 November 2012 - 12:37 PM

View Postjon.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.
Was This Post Helpful? 2
  • +
  • -

#8 chan 06  Icon User is offline

  • D.I.C Head

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

Re: [Help] Converting floats into integer

Posted 26 November 2012 - 09:24 PM

View PostPython_4_President, on 26 November 2012 - 09:45 AM, said:

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

see help(str) for more info.

| 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):
    answer = num1/num2
    return answer


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:
            answer = division(num1, num2)
            print(num1, "/", num2, "=", answer)
            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?
Was This Post Helpful? 0
  • +
  • -

#9 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5441
  • View blog
  • Posts: 11,673
  • Joined: 02-June 10

Re: [Help] Converting floats into integer

Posted 26 November 2012 - 11:14 PM

View Postjon.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?
Was This Post Helpful? 0
  • +
  • -

#10 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7578
  • View blog
  • Posts: 12,742
  • 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.
Was This Post Helpful? 0
  • +
  • -

#11 Blecha  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • 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"


Was This Post Helpful? 1
  • +
  • -

#12 Blecha  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

#13 Blecha  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • 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
Was This Post Helpful? 1
  • +
  • -

#14 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • 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

Was This Post Helpful? 0
  • +
  • -

#15 npanagakis  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • 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 (:
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2