【问题标题】:Float string number to float with 2 decimals? [duplicate]浮点字符串数字以 2 位小数浮动? [复制]
【发布时间】:2018-03-22 13:21:09
【问题描述】:

我有一个函数

def float_():
    price_data = {}
    str_num = '3.505,32'
    price_data['price'] = float(str_num.replace('.','').replace(',','.'))
    price_data['currency'] = 'USD'
    return price_data

还有其他方法可以实现这个浮动结果吗?

【问题讨论】:

  • 你目前的方法没有问题。
  • @MatheusPortela 与 imo 有点不同。

标签: python python-3.x


【解决方案1】:

您可以使用locale.atof,如this question 中所示,它抽象了诸如小数点标点符号和千位分隔符之类的东西:

import locale
locale.setlocale(locale.LC_ALL, 'pt_BR') # Set to the proper language/country

def float_():
    price_data = {}
    str_num = '3.505,32'
    price_data['price'] = locale.atof(str_num)
    price_data['currency'] = 'USD'
    return price_data

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 2018-03-08
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 2016-01-03
    • 2013-08-11
    相关资源
    最近更新 更多