如何使用货币数据类型



如果来自数据库的值是货币数据类型,如何将变量的值固定为小数点后两位数。同样在数据库中,没有为货币数据类型定义精度和小数位数。

Ex. value from database is: 3.7700(of money datatype)
output needed: 3.77

通过输出,我的意思是将值保存在变量中并打印出来。我也把它转换为双倍,然后将其解析为小数点后两位。但我的疑问是,我们是否有任何其他方法可以直接处理货币数据类型而无需类型转换?

如果数据库没有自己的精度,你可以使用你自己的说明符,例如使用System.out.println("%.2f",<money variable>);。 其中 %.2f 用于将限制限制在.之后的 2 位,f 是浮点数据类型的说明符

来自[本网站][1]

[1]: http://www.drdobbs.com/jvm/184405653 我引用以下段落:

`The toDouble() method converts a monetary value to a double floating-point value.
However, you should avoid using the converted value for computational purposes, owing
to the problems associated with the use of floating-point data types with 
monetary data.
You can also convert a monetary value to a long integer data type (having an implied
scaling factor of 2). In this case, an automatic round-off to the nearest whole cent is
performed.`

因此,将您的货币变量转换为具有足够范围的任何类型,您可以使用转换后的值并将小数转换为 2 或您喜欢的任意数量。

请使用java.util.formatter。可以使用类似于"%10.2f"的格式字符串

最新更新