在Java中转换美元(整数)的美元(大十进制)的最佳方法是什么? [英] What is the best way to convert Dollars (Big Decimal) in Cents (Integer) in java?

查看:806
本文介绍了在Java中转换美元(整数)的美元(大十进制)的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将我的Web应用程序与支付网关集成。我想以美元输入总金额,然后将其转换为美分,因为我的支付网关库接受的数量为Cents(类型为 Integer )。我发现java中的 Big Decimal 是操纵货币的最佳方式。目前我接受输入为50美元,并将其转换为整数,如下所示:

I have to integrate my web application with a payment gateway. I want to input total amount in USD and then convert it into Cents as my payment gateway library accepts amount in Cents (of type Integer). I found that Big Decimal in java is best way for manipulation of currency. Currently I take input as say USD 50 and convert it to Integer like this:

BigDecimal rounded = amount.setScale(2, BigDecimal.ROUND_CEILING);
BigDecimal bigDecimalInCents = rounded.multiply(new BigDecimal("100.00"));
Integer amountInCents = bigDecimalInCents.intValue();

这是将USD转换为Cents的正确方法还是应该以其他方式进行?

Is this the correct way of converting USD to Cents or I should do it in some other way?

推荐答案

下面包括我的观点的最简单的是:

The simplest which includes my points below is:

public static int usdToCents(BigDecimal usd) {
    return usd.movePointRight(2).intValueExact();
}

我建议 intValueExact 因为如果信息丢失(如果您处理超过21,474,836.47美元的交易),这将抛出异常。这也可以用来捕获丢失的分数。

I'd recommend intValueExact as this will throw an exception if information will be lost (in case you're processing transactions above $21,474,836.47). This can also be used to trap lost fractions.

我还要考虑接受一个分数和分数的值是否正确。我会说不,客户端代码必须提供有效的可结算金额,所以如果我需要一个自定义异常,我可以这样做:

I'd also consider whether is it correct to accept a value with a fraction of a cent and round. I'd say no, the client code must supply a valid billable amount, so I might do this if I needed a custom exception for that:

public static int usdToCents(BigDecimal usd) {
    if (usd.scale() > 2) //more than 2dp
       thrown new InvalidUsdException(usd);// because was not supplied a billable USD amount
    BigDecimal bigDecimalInCents = usd.movePointRight(2);
    int cents = bigDecimalInCents.intValueExact();
    return cents;
}

这篇关于在Java中转换美元(整数)的美元(大十进制)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆