1

我不知道这是一个问题还是它的方式,但我需要一个小数点后 2 位的值。我可以编写一个函数来将其四舍五入到小数点后 2 位,但是有没有一种解决方案可以让 clojure 本身在添加时处理它。我的意思是改变数据类型或其他东西。

谢谢你。

4

3 回答 3

5

Clojure 在底层使用 java 的标准双精度浮点数(从 1.3 开始),REPL 只打印表示数字所需的数字,所以在这种情况下,它得到 3.0000000 ...但删除了不必要的数字。

您可以使用方便的格式功能控制打印的数字。

(format "%.2f" (+ 1.0 2.0))
> "3.00"
于 2012-07-09T06:27:25.560 回答
5

3.0在 clojure 中是等于3.00,是一个双精度数,如果你想输出一个带 2 位小数的 str,你可以使用 format.

user> (= 3.0 3.00)
true
user> (== 3.0 3.00)
true
user> (format "%.2f" 3.0)
"3.00"
user> (class 3.00)
java.lang.Double
于 2012-07-09T06:31:49.317 回答
2

If you need to do exact decimal arithmetic you can write the numbers with an 'M' suffix to indicate they are exact:

user=> (+ 1.00M 2.00M)
3.00M

But beware, this is much less efficient than using the standard inexact floating point numbers.

于 2012-07-10T11:11:57.410 回答