疯狂python讲义:数字转人民币读法

完善了多个0的情况。测试了几个条件,应该没有什么问题了。有问题欢迎指正修改。

 def divide_num(num):
	int_num=int(num)
	float_num=round((float(num)-int(num))*100)
	return(str(int_num),str(float_num))


han_list=['零','一','二','三','四','五','六','七','八','九']
wei_list=['十','百','千']
def four_to_change(num):
	result=''
	num_len=len(num)
	for i in range(num_len):
		numb=int(num[i])
		if numb != 0 and i != num_len-1:
			result+=han_list[numb]+wei_list[num_len-2-i]
		else:
			result+=han_list[numb]

	if '零零零零' in result:
		result=list(result)
		del result[1:]

	elif '零零零' in result:
		a=result.find('零零零')
		result=list(result)
		if a==0:
			del result[a:a+2]
		else:
			del result[1:] 

	elif '零零' in result:
		a=result.find('零零')
		result=list(result)
		if a==0 and result[-1]=='零':
			del result[-1]
		del result[a]

	elif result[-1]=='零':
		result=list(result)
		del result[-1]
		

	result=''.join(result)
	return result

def inter_to_str(num):
	num_len=len(num)
	if num_len>12:
		print('数字太大,无法计算')
	elif num_len>8:
		if four_to_change(num[-8:-4])=='零':
			return four_to_change(num[:-8])+'亿'+four_to_change(num[-8:-4])+four_to_change(num[-4:])
		else:
			return four_to_change(num[:-8])+'亿'+four_to_change(num[-8:-4])+'万'+four_to_change(num[-4:])
	elif num_len>4:
		return four_to_change(num[-8:-4])+'万'+four_to_change(num[-4:])
	else:
		return four_to_change(num)

num=float(input('请输入一个浮点数:'))
integer,fraction=divide_num(num)
print(inter_to_str(integer))



你可能感兴趣的:(疯狂python讲义:数字转人民币读法)