Search code examples
clojuredecimal

Clojure rounding to decimal places


I have strings which represents the decimal values, ex: "0.010", "0.0100000" "00.01000"

I want to round them to specified format, ex: #.##

In Java we have:

public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
    return setScale(newScale, roundingMode.oldMode);
}

What is the best approach to achieve this in Clojure rather than using interop?


Solution

  • You can use Clojure's format for this purpose. It should provide you a solution to your problem. Here are some examples and a reference:

    user=> (format "%.2f" 0.010)
    "0.01"
    user=> (format "%.2f" 0.010000)
    "0.01"
    user=> (format "%.2f" 00.010000000)
    
    
    user=> (doc format)
    -------------------------
    clojure.core/format
    ([fmt & args])
      Formats a string using java.lang.String.format, see java.util.Formatter for format
      string syntax