2

Is there a way to set the rounding mode in the format function of Clojure? What I would like to achieve is, that the number is not rounded, but "floored" (e.g. 10.126 should become 10.12 and not 10.13).

In other words, I'm looking for something similar as this question / answer, that is, the Clojure equivalent of NumberFormat.setRoundingMode.

Any "pure", built-in Clojure solution is fine, though it does not necessarily have to be with format.

Out of scope is the following, (although I'm aware they are also workable solutions):

  • Using any Java classes (as I said, I'm looking for for a pure and built-in Clojure-solution)
  • Converting the float to string, and back to float with the current number of decimals (I'm doing this currently, and was wondering if there is a better way).

N.B.: In case this is not possible at all with a built-in Clojure function (which I'm beginning to suspect), then a link to some documentation confirming this is also a valid answer for me.

Alex Miller
  • 69,183
  • 25
  • 122
  • 167
Attilio
  • 1,624
  • 1
  • 17
  • 27
  • Related, but not duplicate: http://stackoverflow.com/questions/10751638/clojure-rounding-to-decimal-places (that question is about rounding, not flooring!) – Attilio Jan 18 '17 at 21:45

1 Answers1

1

format uses String.format(), which uses Formatter, which afaict does not support any rounding mode except HALF_UP.

The DecimalFormat format supports all the rounding modes, like floor so that would be one option, although you would need to use Java interop.

Another option is the Common Lisp derived cl-format, however afaict cl-format also does not support specifying a rounding mode (and even allows impls to pick in Common Lisp).

And finally another option might be to round the number first before printing it. Seems like with-precision might be helpful with that, but I didn't manage to get it to do what I want. Really this is just tapping into BigDecimal rounding capabilities.

Alex Miller
  • 69,183
  • 25
  • 122
  • 167