在java中使用BigDecimal实现商品的价格
在 Web 应用程序中,我想对具有价格字段的 ItemForSale 进行建模。我在其他地方读到,由于舍入错误,float 或 double 不应该用于货币字段,而 BigDecimal 是适合此类型的类型目的。我创建了这些类,
class ItemForSale {
private String name;
private BigDecimal price;
...
}
class MyUtils{
...
public static BigDecimal parsePriceOfItem(String priceStr){
BigDecimal price;
BigDecimal zero = new BigDecimal(0);
try{
price = new BigDecimal(priceStr);
}catch(NumberFormatException nfe){
price = zero;
}
if(price.doubleValue() < zero.doubleValue()){
price = zero;
}
return price;
}
}
这是解析价格字符串(由用户输入)的正确方法吗?我想将负数和无效字符串(例如“abcd”)视为 0。
如果有更好的方法,请告诉我
谢谢马克
In a web application ,I want to model an ItemForSale which has a price field.I read elsewhere that float or double should not be used for currency fields due to rounding errors and BigDecimal is the proper type for this purpose.I created these classes
class ItemForSale {
private String name;
private BigDecimal price;
...
}
class MyUtils{
...
public static BigDecimal parsePriceOfItem(String priceStr){
BigDecimal price;
BigDecimal zero = new BigDecimal(0);
try{
price = new BigDecimal(priceStr);
}catch(NumberFormatException nfe){
price = zero;
}
if(price.doubleValue() < zero.doubleValue()){
price = zero;
}
return price;
}
}
Is this the right way to parse a price string(as entered by user)?I wanted to treat negative and invalid strings (say 'abcd') as 0.
If there is a better way ,please tell me
thanks
mark
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么要将无效输入视为 0?当然,您想告诉用户他们犯了一个错误,而不是将其视为他们输入了零。
如果您正在解析用户输入,则可能应该使用
DecimalFormat
而不是BigDecimal
构造函数 - 这样它将使用适当的文化信息。 (使用setParseBigDecimal
使DecimalFormat
解析为BigDecimal
而不是double
。)然后将 BigDecimal 值转换为双打,使用:
我建议您应该向用户指示三种不同的状态:
Why would you want to treat invalid input as 0? Surely you'd want to tell the user that they've made a mistake, rather than treating it as if they'd typed in zero.
If you're parsing user input, you should probably be using
DecimalFormat
instead of theBigDecimal
constructor - that way it will use the appropriate cultural information. (UsesetParseBigDecimal
to makeDecimalFormat
parse toBigDecimal
instead ofdouble
.)Then instead of converting the BigDecimal values to doubles, use:
I would suggest that you should indicate to the user three different states:
您最昂贵的物品有多贵?如果低于 21,474,836.47 美元,您可以安全地将价格表示为普通
int
中保存的美分数。您避免
float
和double
是正确的。通常的解决方案是使用int
或long
来保存分数并相应地调整输出格式。通常无需考虑BigDecimal
的复杂性和速度问题。How costly is your most expensive item? If it is less than $21,474,836.47 you can safely express the price as a number of cents held in a normal
int
.You are correct to avoid
float
anddouble
. The usual solution is to use anint
, or along
, to hold the number of cents and adjust output formatting accordingly. There is usually no need to get into the complexities, and speed issues, ofBigDecimal
.这是我的建议:
Here's my suggestion: