PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How can I get Python to recognize comma as the decimal point in user input?

 August 10, 2022     decimal, floating-point, python     No comments   

Issue

Super beginner here.

I'm following along the Automate the Boring Stuff With Python book and I decided to make a little script to help me out with some basic percentage checking. I didn't want to open Excel everytime I wanted to do this.

So the script gets two inputs, an old price and a new price and then calculates the percentage change in price. I think I got that right.

The problem occurs once I try to enter a float (that's the right term, yeah?) and I use the comma here in Europe.

I found a topic here where a similar question was answered, but there seems to be an issue on whether or not to call setlocale and (as far as I understand it) it does not deal with how to convert an input?

My code is below:

    def izracun_odstotkov():    #function to calculate the difference in % between original price and new price
    while True:
        try:
            prvotna_cena = float(input('Prosim vnesi prvotno ceno:')) #original price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue

        if prvotna_cena == 0:
                print('Prvotna cena ne more biti 0.')
        else:
            break

    while True:
        try:
            nova_cena = float(input('Prosim vnesi novo ceno:')) #new price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue
        else:
            break

    print(round((float (nova_cena)- float (prvotna_cena))/ float (prvotna_cena)*100, 2), '%')

while True:
    izracun_odstotkov() #This makes the script run over and over so the user can just keep checking the % changes.

Solution

You can use the replace method:

prvotna_cena = float(input('Prosim vnesi prvotno ceno:').replace(',','.'))


Answered By - Ann Zen
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing