0

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

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

output needed: 3.77

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

4

2 回答 2

0

如果数据库没有自己的精度,您可以使用自己的说明符,例如 use System.out.println("%.2f",<money variable>);。where%.2f用于将限制限制在 and 之后的 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 或您喜欢的任意位数。

于 2012-04-26T11:49:15.497 回答
0

请使用 java.util.formatter。您可以使用像“%10.2f”这样的格式化字符串

于 2012-04-26T11:47:45.997 回答