简体   繁体   中英

converting currency in java from float to integer

I am trying to convert currency(float number, dollar, cent) in Java to integer(only cent) on the following way:

1.01 = 101
1.99 = 199

and so on

What would be the easiest way?

Thanks.

Something like:

public int convertDollarsToCents(float dollars) {
    return Math.round(dollars * 100f);
}

Be careful when dealing with currency. It's not recommended to keep money as a floating-point value, but if you no say in how it was stored and want to convert it to cents, round the value after multiplication.

int cents = Math.round(money*100f);

Without rounding you'll truncate the value which will result in off-by-one cent errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM