在 JTable 中显示金钱,但保留按双精度排序的能力
我有一个 JTable,其中一列是以美元和美分表示的金额。我将此 TableColumn 定义为 Double ,它右对齐,并且在排序时,它将其排序为 double (而不是字符串)。这一切都很好。 我现在的问题是它截断了尾随零。 100.00 显示为 100 0.00 显示为 0 等。我尝试了 TableCellRenderer,但尽管这会导致资金列显示尾随零,但金额现在全部左对齐,并且 JTable 将其视为字符串。
我希望在显示中保留尾随零,但也希望保留数据类型,以便进行排序和右对齐。如果有更好的方法,数据类型不需要是双精度型。
I have a JTable where one of the columns is an amount in dollars and cents. I define this TableColumn as a Double and it right justifies and when sorting, it sorts it as a double (not as a string). This is all well and good.
My problem now is that it truncates trailing zeros. 100.00 is displayed as 100 0.00 is displayed as 0, etc. I tried a TableCellRenderer but although this causes the money column to display with trailing zeros, the amounts are now all left justified and the JTable sees this as a string.
I want the trailing zeros to be retained in displays but also to retain the data type so that sorting and right justifying occur. The datatype does not need to be a double if there is a better way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了完美的链接。这是第一次。只需复制代码即可。
http://tips4java.wordpress.com/2008/10/11/表格格式渲染器/
I found the perfect link. This worked first time. Just copy the code.
http://tips4java.wordpress.com/2008/10/11/table-format-renderers/
如果你想精确地处理金钱,你应该将其表示为美分和整数,如果你必须处理大量资金,则应将其表示为 BigInt。浮点数可能会导致问题,因为它们会遇到精度问题,
这将保留您能够进行排序,消除尾随零的问题,为您提供所需的精度,并且使用自定义渲染器,您可以获得所需的小数点。
If you want to handle money precisely, you should represent it as cents and Integers, or BigInts if you have to handle huge amounts. Floating point numbers can cause problems because they suffer from precision problems
This will preserve your ability to sort, remove the problem of trailing zeroes, give you the precision you need, and with a custom renderer, you can get the decimal point where it needs to be.