Groovy 默认情况下在 Map 中将数字值视为大十进制

标签 groovy

我在 groovy 中创建了一个 map :

def measureMap = [:]
measureMap.put('engine.temperature', 70.0)
measureMap.put('fuel.level', 71.0)

此 map 的值被视为 Bigdecimal。

有什么原因吗。

为什么我问这个我知道层次结构

java.lang.Object
java.lang.Number
java.math.BigDecimal

所以我认为默认情况下它应该将其视为 double/float 。

最佳答案

默认情况下,Groovy 使用 BigDecimal 作为十进制数。这是 documented :

Conveniently for exact decimal number calculations, Groovy choses java.lang.BigDecimal as its decimal number type. In addition, both float and double are supported, but require an explicit type declaration, type coercion or suffix. Even if BigDecimal is the default for decimal numbers, such literals are accepted in methods or closures taking float or double as parameter types.

如果您需要您的值在映射中是双类型的,您可以为 double /浮点文字添加熟悉的 DF 后缀:

measureMap.put('engine.temperature', 70.0d) //java.lang.Double
measureMap.put('engine.temperature', 71.0f) //java.lang.Float

关于Groovy 默认情况下在 Map 中将数字值视为大十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57176809/

相关文章:

json - 使用gson Grails View 序列化Map <FooCategory,List <Foo >>

grails - 域对象上的 Class.forName newInstance 不是来自 grails 外部的 GroovyObject

java - 如何在Java中运行groovy

gradle - 存储库中的文件,阻止IntelliJ使用星号导入

grails - 有诸如groovy xml-rpc请求构建器之类的东西吗?

grails - Groovy markupBuilder更新父节点

java - 正则表达式匹配包含非重复单词的字符串

java - Groovy 闭包可以扩展抽象类吗

elasticsearch - Elasticsearch中的聚合和排序

grails - 我应该使用哪个版本的Grails?