Clojure 四舍五入到小数位 [英] Clojure rounding to decimal places

查看:19
本文介绍了Clojure 四舍五入到小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代表十进制值的字符串,例如:0.010"、0.0100000"、00.01000"

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

我想将它们四舍五入到指定的格式,例如:#.##

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

在 Java 中,我们有:

In Java we have:

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

在 Clojure 中实现这一目标而不是使用互操作的最佳方法是什么?

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

推荐答案

为此您可以使用 Clojure 的 format.它应该为您提供解决问题的方法.以下是一些示例和参考:

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

这篇关于Clojure 四舍五入到小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆