使用 Android DataBinding 时强制点(“.”)作为小数点分隔符

Force point (“.”) as decimal separator while using Android DataBinding

我正在尝试从 API 格式化双精度数,因此它只显示前 2 位小数。此外,我正在使用 DataBinding 执行此操作。当我这样做时,它起作用了:

android:text='@{String.format("%.2f", cartItem.totalPrice)}'

但是,这将使用逗号 , 作为小数点分隔符。当我试图强制它使用点 . 作为小数点分隔符时,我无法构建项目,因为我收到 DataBinding 错误。这就是我想要做的:

android:text='@{String.format(Locale.ROOT, "%.2f", cartItem.totalPrice)}'

But, this will use comma , as a decimal separator.

此处不能使用逗号。这个点不是小数分隔符,而是关于输出精度的格式说明符的一部分 (see docs)。因此,一旦获得输出,您只需将 . 替换为 ,,例如:

android:text='@{String.format("%.2f", cartItem.totalPrice).replace(".", ",")}'

以逗号分隔符结尾。