【问题标题】:How do I trim the decimal of a number using clojure or jython?如何使用 clojure 或 jython 修剪数字的小数点?
【发布时间】:2011-02-21 23:32:20
【问题描述】:

在 clojure 或 jython 中: 说我有一个号码 4.21312312312312 我怎样才能得到一个只有前 2 位小数的数字。对于上面的示例,它将返回 4.21。 谢谢

【问题讨论】:

标签: clojure decimal jython


【解决方案1】:

Clojure 在 clojure.contrib.math 中有一个 round 函数 - 如果您希望 Clojure 可以处理的所有不同可能的数值类型具有正确的行为,那么最好使用这个函数。

在这种情况下,假设您希望结果为任意精度的 BigDecimal,一个简单的方法是构建一个小辅助函数,如下所示:

(use 'clojure.contrib.math)

(defn round-places [number decimals]
  (let [factor (expt 10 decimals)]
    (bigdec (/ (round (* factor number)) factor))))

(round-places 4.21312312312312 2)
=> 4.21M   

【讨论】:

  • 我是 Clojure 新手,请问如何为 Clojure 安装贡献的库?当我运行您的代码时,我得到了这个: user=> (use 'clojure.contrib.math) FileNotFoundException Could not locate clojure/contrib/math__init.class or clojure/contrib/math.clj on classpath: cloj ure.lang.RT .load (RT.java:443) 用户=> 谢谢!
  • 对于尼克的问题,clojure.contrib.math 现在是 clojure.math.numeric-tower。如果您使用 Leiningen,则需要将其包含在依赖项中:[org.clojure/math.numeric-tower "0.0.4"],或者使用更高版本号的相同内容。
  • 我的版本 (defn round-places [number decimals] (let [factor (Math/pow 10 decimals)] (double (/ (Math/round (* factor number)) factor)))) 使用 java.lang.math
【解决方案2】:

我想我在进一步研究后得到了这个

(format "%.2f"  4.21312312312312)

应该返回 4.21

【讨论】:

  • 这是数字的字符串表示形式,而不是数字本身。
【解决方案3】:

乘以你想要的10^numberofdecimals,四舍五入,然后除。这并不能保证字符串表示将被正确舍入,但在大多数情况下应该可以工作。例如:

(* 0.01 (Math/round (* 100 (float (/ 7 8)))))

屈服0.88

【讨论】:

    【解决方案4】:

    更进一步,您可以参数化小数位数:

    (defn- factor [no-of-decimal-places]
        (.pow (BigInteger. "10") no-of-decimal-places))
    
    (defn truncate [value decimal-places]
      (let [divide-and-multiply-by (factor decimal-places)]
        (float (/ (int (* divide-and-multiply-by value)) divide-and-multiply-by))))
    
    (truncate 2.23999999 2)
    => 2.23
    
    (truncate 2.23999999 3)
    => 2.239
    
    (truncate 2.23999999 4)
    => 2.2399
    

    【讨论】:

      【解决方案5】:

      发现此线程正在寻找类似的截断答案。

      不确定是否有更好的解决方案,但想出了以下方法。

      对于非四舍五入,您可以乘以 100(2 位小数,1000 以 3 等),转换为整数,然后除以原始因子,然后转换为浮点数输出。例如:

      (float (/ (int (* 100 123.1299)) 100))
      => 123.12
      
      (float (/ (int (* 100 123.1209)) 100))
      => 123.12
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-18
        • 2011-06-09
        • 1970-01-01
        相关资源
        最近更新 更多