Converting input containing special character to float












-1















This is the beginning of my program that calculates simple interest. Interest rate will have the following format : 0.97 , 0.67 , 0.17 etc. They won't be bigger than 1. So if the user enter 9 for the interest, program will convert it to 0.09 (by dividing it by 100) . Also user can enter input using '/'. So program will convert input like 97/100 to 0.97.



I wrote the code below. It works but it seems to me that there might be a easier and more elegant solution to this. Maybe using more build-in functions etc. If you help me with that I would be very appreciated.



def toNum(interest):

if '/' not in interest:
if float(interest) > 1:
return float(interest)/100

else:
return float(interest)


else:
l=
n = 0
count = 1

list_interest=
for e in interest:
list_interest.append(e)

for e in list_interest:

if count == 1 or count == 3:
l.append(e)
count = count +1
continue


if e == '/':
n = n + 1
count = count +1
else:
l[n] = l[n] + e

return int(l[0]) / int(l[1])






interest = input("Interest rate: ")






print(toNum(interest))









share|improve this question


















  • 1





    What exactly is your question? If your code is working, then codereview.stackexchange.com might be the place to ask for input.

    – Mike Scotty
    Nov 26 '18 at 13:07











  • I didn't know this site exists, thank you

    – ikadorus
    Nov 26 '18 at 13:13
















-1















This is the beginning of my program that calculates simple interest. Interest rate will have the following format : 0.97 , 0.67 , 0.17 etc. They won't be bigger than 1. So if the user enter 9 for the interest, program will convert it to 0.09 (by dividing it by 100) . Also user can enter input using '/'. So program will convert input like 97/100 to 0.97.



I wrote the code below. It works but it seems to me that there might be a easier and more elegant solution to this. Maybe using more build-in functions etc. If you help me with that I would be very appreciated.



def toNum(interest):

if '/' not in interest:
if float(interest) > 1:
return float(interest)/100

else:
return float(interest)


else:
l=
n = 0
count = 1

list_interest=
for e in interest:
list_interest.append(e)

for e in list_interest:

if count == 1 or count == 3:
l.append(e)
count = count +1
continue


if e == '/':
n = n + 1
count = count +1
else:
l[n] = l[n] + e

return int(l[0]) / int(l[1])






interest = input("Interest rate: ")






print(toNum(interest))









share|improve this question


















  • 1





    What exactly is your question? If your code is working, then codereview.stackexchange.com might be the place to ask for input.

    – Mike Scotty
    Nov 26 '18 at 13:07











  • I didn't know this site exists, thank you

    – ikadorus
    Nov 26 '18 at 13:13














-1












-1








-1








This is the beginning of my program that calculates simple interest. Interest rate will have the following format : 0.97 , 0.67 , 0.17 etc. They won't be bigger than 1. So if the user enter 9 for the interest, program will convert it to 0.09 (by dividing it by 100) . Also user can enter input using '/'. So program will convert input like 97/100 to 0.97.



I wrote the code below. It works but it seems to me that there might be a easier and more elegant solution to this. Maybe using more build-in functions etc. If you help me with that I would be very appreciated.



def toNum(interest):

if '/' not in interest:
if float(interest) > 1:
return float(interest)/100

else:
return float(interest)


else:
l=
n = 0
count = 1

list_interest=
for e in interest:
list_interest.append(e)

for e in list_interest:

if count == 1 or count == 3:
l.append(e)
count = count +1
continue


if e == '/':
n = n + 1
count = count +1
else:
l[n] = l[n] + e

return int(l[0]) / int(l[1])






interest = input("Interest rate: ")






print(toNum(interest))









share|improve this question














This is the beginning of my program that calculates simple interest. Interest rate will have the following format : 0.97 , 0.67 , 0.17 etc. They won't be bigger than 1. So if the user enter 9 for the interest, program will convert it to 0.09 (by dividing it by 100) . Also user can enter input using '/'. So program will convert input like 97/100 to 0.97.



I wrote the code below. It works but it seems to me that there might be a easier and more elegant solution to this. Maybe using more build-in functions etc. If you help me with that I would be very appreciated.



def toNum(interest):

if '/' not in interest:
if float(interest) > 1:
return float(interest)/100

else:
return float(interest)


else:
l=
n = 0
count = 1

list_interest=
for e in interest:
list_interest.append(e)

for e in list_interest:

if count == 1 or count == 3:
l.append(e)
count = count +1
continue


if e == '/':
n = n + 1
count = count +1
else:
l[n] = l[n] + e

return int(l[0]) / int(l[1])






interest = input("Interest rate: ")






print(toNum(interest))






python python-3.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 26 '18 at 13:01









ikadorusikadorus

134




134








  • 1





    What exactly is your question? If your code is working, then codereview.stackexchange.com might be the place to ask for input.

    – Mike Scotty
    Nov 26 '18 at 13:07











  • I didn't know this site exists, thank you

    – ikadorus
    Nov 26 '18 at 13:13














  • 1





    What exactly is your question? If your code is working, then codereview.stackexchange.com might be the place to ask for input.

    – Mike Scotty
    Nov 26 '18 at 13:07











  • I didn't know this site exists, thank you

    – ikadorus
    Nov 26 '18 at 13:13








1




1





What exactly is your question? If your code is working, then codereview.stackexchange.com might be the place to ask for input.

– Mike Scotty
Nov 26 '18 at 13:07





What exactly is your question? If your code is working, then codereview.stackexchange.com might be the place to ask for input.

– Mike Scotty
Nov 26 '18 at 13:07













I didn't know this site exists, thank you

– ikadorus
Nov 26 '18 at 13:13





I didn't know this site exists, thank you

– ikadorus
Nov 26 '18 at 13:13












3 Answers
3






active

oldest

votes


















0














This seems to do what you've accomplished, and is reasonably compact.



EDIT added in a recursive function call, because I realised the if/else wasn't really necessary because you can just feed the numerator back in. This assumes, of course, that the numerator/denominator always uses 100 as its denominator.



It determines whether it's possible to float the input. If it can it either divides by 100 or returns, depending on whether the value is > 1. If an Exception is raised (in your case, meaning that the user has entered "97/100" or similar) it parses this out and returns the calculated rate.



There are a bunch of edge cases where this would fail, but it's something to build on/consider.



def toNum(interest):

try:
floated = float(interest)
if floated > 1:
rate = floated / 100
elif floated < 1:
rate = floated
return rate
except ValueError:
return toNum(interest.split("/")[0])





share|improve this answer


























  • thank you for your help

    – ikadorus
    Nov 26 '18 at 13:30



















0














I guess the following might work:



import re
interest = re.sub('[^0-9.0-9]+', '', interest)
print(toNum(interest))





share|improve this answer































    0














    You have two cases, the input is purely numeric, or it is a fraction notation. So check if you have a fraction:



    def toNum(user_input):
    if '/' in user_input:
    return abs(eval(user_input))

    if user_input.isnumeric():
    return int(user_input)/100

    raise AttributeError('`user_input` must be an integer 0-100 or fraction')


    Since isnumeric() will return false if they input -1 or some garbage like that you're safe there.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53481708%2fconverting-input-containing-special-character-to-float%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      This seems to do what you've accomplished, and is reasonably compact.



      EDIT added in a recursive function call, because I realised the if/else wasn't really necessary because you can just feed the numerator back in. This assumes, of course, that the numerator/denominator always uses 100 as its denominator.



      It determines whether it's possible to float the input. If it can it either divides by 100 or returns, depending on whether the value is > 1. If an Exception is raised (in your case, meaning that the user has entered "97/100" or similar) it parses this out and returns the calculated rate.



      There are a bunch of edge cases where this would fail, but it's something to build on/consider.



      def toNum(interest):

      try:
      floated = float(interest)
      if floated > 1:
      rate = floated / 100
      elif floated < 1:
      rate = floated
      return rate
      except ValueError:
      return toNum(interest.split("/")[0])





      share|improve this answer


























      • thank you for your help

        – ikadorus
        Nov 26 '18 at 13:30
















      0














      This seems to do what you've accomplished, and is reasonably compact.



      EDIT added in a recursive function call, because I realised the if/else wasn't really necessary because you can just feed the numerator back in. This assumes, of course, that the numerator/denominator always uses 100 as its denominator.



      It determines whether it's possible to float the input. If it can it either divides by 100 or returns, depending on whether the value is > 1. If an Exception is raised (in your case, meaning that the user has entered "97/100" or similar) it parses this out and returns the calculated rate.



      There are a bunch of edge cases where this would fail, but it's something to build on/consider.



      def toNum(interest):

      try:
      floated = float(interest)
      if floated > 1:
      rate = floated / 100
      elif floated < 1:
      rate = floated
      return rate
      except ValueError:
      return toNum(interest.split("/")[0])





      share|improve this answer


























      • thank you for your help

        – ikadorus
        Nov 26 '18 at 13:30














      0












      0








      0







      This seems to do what you've accomplished, and is reasonably compact.



      EDIT added in a recursive function call, because I realised the if/else wasn't really necessary because you can just feed the numerator back in. This assumes, of course, that the numerator/denominator always uses 100 as its denominator.



      It determines whether it's possible to float the input. If it can it either divides by 100 or returns, depending on whether the value is > 1. If an Exception is raised (in your case, meaning that the user has entered "97/100" or similar) it parses this out and returns the calculated rate.



      There are a bunch of edge cases where this would fail, but it's something to build on/consider.



      def toNum(interest):

      try:
      floated = float(interest)
      if floated > 1:
      rate = floated / 100
      elif floated < 1:
      rate = floated
      return rate
      except ValueError:
      return toNum(interest.split("/")[0])





      share|improve this answer















      This seems to do what you've accomplished, and is reasonably compact.



      EDIT added in a recursive function call, because I realised the if/else wasn't really necessary because you can just feed the numerator back in. This assumes, of course, that the numerator/denominator always uses 100 as its denominator.



      It determines whether it's possible to float the input. If it can it either divides by 100 or returns, depending on whether the value is > 1. If an Exception is raised (in your case, meaning that the user has entered "97/100" or similar) it parses this out and returns the calculated rate.



      There are a bunch of edge cases where this would fail, but it's something to build on/consider.



      def toNum(interest):

      try:
      floated = float(interest)
      if floated > 1:
      rate = floated / 100
      elif floated < 1:
      rate = floated
      return rate
      except ValueError:
      return toNum(interest.split("/")[0])






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 26 '18 at 13:32

























      answered Nov 26 '18 at 13:25









      AndrewAndrew

      634312




      634312













      • thank you for your help

        – ikadorus
        Nov 26 '18 at 13:30



















      • thank you for your help

        – ikadorus
        Nov 26 '18 at 13:30

















      thank you for your help

      – ikadorus
      Nov 26 '18 at 13:30





      thank you for your help

      – ikadorus
      Nov 26 '18 at 13:30













      0














      I guess the following might work:



      import re
      interest = re.sub('[^0-9.0-9]+', '', interest)
      print(toNum(interest))





      share|improve this answer




























        0














        I guess the following might work:



        import re
        interest = re.sub('[^0-9.0-9]+', '', interest)
        print(toNum(interest))





        share|improve this answer


























          0












          0








          0







          I guess the following might work:



          import re
          interest = re.sub('[^0-9.0-9]+', '', interest)
          print(toNum(interest))





          share|improve this answer













          I guess the following might work:



          import re
          interest = re.sub('[^0-9.0-9]+', '', interest)
          print(toNum(interest))






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 26 '18 at 13:10









          JerilJeril

          2,0531630




          2,0531630























              0














              You have two cases, the input is purely numeric, or it is a fraction notation. So check if you have a fraction:



              def toNum(user_input):
              if '/' in user_input:
              return abs(eval(user_input))

              if user_input.isnumeric():
              return int(user_input)/100

              raise AttributeError('`user_input` must be an integer 0-100 or fraction')


              Since isnumeric() will return false if they input -1 or some garbage like that you're safe there.






              share|improve this answer




























                0














                You have two cases, the input is purely numeric, or it is a fraction notation. So check if you have a fraction:



                def toNum(user_input):
                if '/' in user_input:
                return abs(eval(user_input))

                if user_input.isnumeric():
                return int(user_input)/100

                raise AttributeError('`user_input` must be an integer 0-100 or fraction')


                Since isnumeric() will return false if they input -1 or some garbage like that you're safe there.






                share|improve this answer


























                  0












                  0








                  0







                  You have two cases, the input is purely numeric, or it is a fraction notation. So check if you have a fraction:



                  def toNum(user_input):
                  if '/' in user_input:
                  return abs(eval(user_input))

                  if user_input.isnumeric():
                  return int(user_input)/100

                  raise AttributeError('`user_input` must be an integer 0-100 or fraction')


                  Since isnumeric() will return false if they input -1 or some garbage like that you're safe there.






                  share|improve this answer













                  You have two cases, the input is purely numeric, or it is a fraction notation. So check if you have a fraction:



                  def toNum(user_input):
                  if '/' in user_input:
                  return abs(eval(user_input))

                  if user_input.isnumeric():
                  return int(user_input)/100

                  raise AttributeError('`user_input` must be an integer 0-100 or fraction')


                  Since isnumeric() will return false if they input -1 or some garbage like that you're safe there.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 26 '18 at 14:33









                  BorisuBorisu

                  49028




                  49028






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53481708%2fconverting-input-containing-special-character-to-float%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Contact image not getting when fetch all contact list from iPhone by CNContact

                      count number of partitions of a set with n elements into k subsets

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks