【问题标题】:What is the swift code to apply Round Up or Down Sum Amount?申请向上或向下总金额的快速代码是什么?
【发布时间】:2016-07-01 21:40:22
【问题描述】:

我尝试使用 Xcode - Playground。

这是我的代码。初学者。

======== 导入 UIKit

var num1 : Double = 0.055  // Stock Price
var num2 : Double = 18     // Lots
var num3 : Double = 1000   // Share Per Lots

var sum1 : Double = num1 * num2 * num3    // Gross Share Price

var sum5 : Double = sum1 * (0.03/100) // Clearing Charges  // Answer Playground Return is " 0.297 "

我的问题是“sum5”,我想要回答四舍五入并显示“0.30”

在swift代码中可以吗?

谢谢。

【问题讨论】:

    标签: swift decimal


    【解决方案1】:

    关于那个answer

    如果你需要四舍五入到一个特定的地方,那么你乘以pow(10.0, numberOfPlaces)round,然后除以pow(10, numberOfPlaces)。在你的情况下,地方的数量是2.0

    let numberOfPlaces = 2.0
    let multiplier = pow(10.0, numberOfPlaces)
    let rounded = round(sum5 * multiplier) / multiplier
    print(rounded) // 0.3
    

    如果你有一个像sum5 = 0.3465 这样的数字并且你想四舍五入到小数点后的第三位,你可以使用3.0 作为numberOfPlaces 并得到结果0.347

    【讨论】:

      【解决方案2】:

      你可以这样得到它:

      var roundOfSum5 : Double = Double(round(100 * sum5)/100)  //0.3
      

      【讨论】:

      • 非常感谢 swift 的帮助。有效。感谢 Dharmesh Kheni。
      • 很高兴为您提供帮助.. :)
      猜你喜欢
      • 1970-01-01
      • 2019-12-13
      • 2015-03-13
      • 2012-01-11
      • 2018-08-14
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多