在Python中将一个浮点数转换为字符串时保留小数位
我正在为学校编写一个ATM程序。我一直在进行大量的研究,试图弄清楚为什么当我的数字是100.00时,当他们被当作字符串时,他们变成了100.0。我尝试过很多不同的东西,但总是会出错。 import sys #account balance acct_bal = float(500.25) deposit_amount = float(0.00) balance = float(0.00) withdrawal_amount = float(0.00) #<--------functions go here--------------------> #printbalance function, choice B def account_balance(acct_bal): print("Your current balance:") print(acct_bal) #deposit function, choice D def deposit(deposit_amount, balance): print("Deposit was $" + str(float(deposit_amount)) + ", current balance is $" + str(float(balance))) #print("Deposit was $" + "{:,.2f}".format(deposit_amount) + ", current balance is $" + "{:,.2f}".format(balance)) #This one causes an error #Traceback (most recent call last): #File "G:/SNHU/1 - CURRENT/IT-140 Introduction to Scripting Python (10-30-17 to 12-24-17)/Module 5/ATM", line 29, in <module> #deposit(deposit_amount, balance) #File "G:/SNHU/1 - CURRENT/IT-140 Introduction to Scripting Python (10-30-17 to 12-24-17)/Module 5/ATM", line 17, in deposit #print("Deposit was $" + "{:,.2f}".format(deposit_amount) + ", current balance is $" + "{:,.2f}".format(balance)) #ValueError: Unknown format code 'f' for object of type 'str' #withdraw function, choice W def withdrawal(withdrawal_amount, balance): print("Withdrawal amount was $" + str(float(withdrawal_amount)) + ", current balance is $" + str(float(balance))) #User Input goes here, use if/else conditional statement to call function based on user input userchoice = input("What would you like to do?\n") if (userchoice == "D"): deposit_amount = input("How much would you like to deposit today?\n") balance = acct_bal + float(deposit_amount) deposit(deposit_amount, balance) elif (userchoice == "B"): account_balance(acct_bal) else: withdrawal_amount = input("How much would you like to withdraw?\n") balance = acct_bal - float(withdrawal_amount) withdrawal(withdrawal_amount, balance) 这是输出我得到: What would you like to do? W How much would you like to withdraw? 100 Withdrawal amount was $100.0, current balance is $400.25 应> Withdrawal amount was $100.00, current balance is $400.25 过程中,如果您正在使用Python 3.X然后退出代码为0
...全文
相关推荐
python 正确保留多位小数的实例
今天小编就为大家分享一篇python 正确保留多位小数的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
python十进制和二进制的转换方法(含浮点数)
主要介绍了python十进制和二进制的转换方法(含浮点数),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
保留浮点数的n位小数()
保留浮点数的n位小数; 源码; 西门子1200,博图V14sp1;
python中精确输出JSON浮点数的方法
有时需要在JSON中使用浮点数,比如价格、坐标等信息。但python中的浮点数相当不准确, 例如下面的代码:复制代码 代码如下:#!/usr/bin/env python import json as json data = [ 0.333, 0.999, 0.1 ]print json.dumps(data)输出结果如下:复制代码 代码如下:$ python floatjson.py[0.33300000000000002, 0.999, 0.10000000000000001]能不能指定浮点数的输出格式,比如精确到小数点后两位呢?有个简单的方法,虽然比较dirty:复制代码 代码如下:#!
python 保存float类型的小数的位数方法
今天小编就为大家分享一篇python 保存float类型的小数的位数方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧


其他技术讨论专区
