我有一个可以是正数或负数的双精度值,我想按以下方式显示:
对于正值:
+1.10美元
对于负值:
-0.50美元
0值为空
我这样试过:

Double surcharge = ...
if(surcharge < 0){
    cell.lblSurcharge.text = "-$" + String(format:"%.02f", surcharge)
}else if(surcharge > 0){
    cell.lblSurcharge.text = "+$" + String(format:"%.02f", surcharge)
}else{
    cell.lblSurcharge.text = nil
}

但对于负值,它显示如下:
-0.50美元
如何正确设置格式,或从双精度中删除“-”?

最佳答案

你知道surcharge在这一点上是负数,所以只需添加-使其对格式是正数。此外,还可以将"-$"移到格式字符串中:
更改:

cell.lblSurcharge.text = "-$" + String(format:"%.02f", surcharge)

致:
cell.lblSurcharge.text = String(format:"-$%.02f", -surcharge)

若要在一行中完成所有操作,请使用三元运算符(?:)处理零并将符号添加到格式字符串:
cell.lblSurcharge.text = surcharge == 0 ? "" : String(format:"%@$%.02f", surcharge > 0 ? "+" : "-", abs(surcharge))

关于swift - 将Double设置为负货币格式,或从Double中删除“-”号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51923138/

10-12 14:33