你如何截断将一组数字相加到8位小数的结果呢?

时间:2018-01-11 08:15:07

标签: clojure

对于我的加密货币交易程序,我想将所有浮点数截断到恰好8个位置。我怎么能在Clojure中做到这一点?

以下是相关的代码示例:

(with-precision 8 :rounding DOWN
  (bigdec 
   (+ 0.2
      0.0109     ; 1/1
      0.0285     ; 1/2
      0.02858    ; 1/3
      0.01963    ; 1/4
      0.00392977 ; 1/5
      0.00956410 ; 1/6
      0.02322879 ; 1/7
      0.01547502 ; 1/8
      0.01616702 ; 1/9
      0.01463114 ; 1/10
      0.00843843 ; 1/11
      0.01162393 ; 1/12
      )))

目前返回0.39066819999999997,但我希望它返回0.39066819

1 个答案:

答案 0 :(得分:9)

I would use with-precision which allows you to specify the precision and rounding mode for your math operations with BigDecimal numbers - and you should use them instead of floating point numbers for handling currency amounts. Notice that M in the number literal indicates it's a BigDecimal value. You can coerce your numbers to BigDecimal with bigdec. If you would like to literally truncate the result you need to use DOWN rounding mode.

(with-precision 3 :rounding DOWN
  (+ (bigdec 0.1111111111) 0.22222222M))
;; => 0.333M

Make sure that your operations are done on BigDecimals as the conversion to bigdec is not impacted by with-precision:

(with-precision 3 :rounding DOWN
  (bigdec 0.11111111))
;; => 0.11111111M

(with-precision 3 :rounding DOWN
  (* 1M (bigdec 0.11111111)))
;; => 0.111M

If you would like to modify the BigDecimal value directly you need to use Java interop (either via BigDecimal constructor accepting properly configured MathContext or by calling .round instance method).