To convert a double representing a price into a String without a decimal point (effectively, as cents), you should use BigDecimal to avoid floating-point precision issues that double can introduce, especially with financial calculations.
Here's the recommended approach:
java
import java.math.BigDecimal;
import java.math.RoundingMode;
public class PriceConverter {
/**
* Converts a double representing a price (e.g., 12.50) to a String
* representing the price in cents without a decimal point (e.g., "1250").
*
* This method uses BigDecimal for accurate financial calculations.
* It handles rounding to two decimal places before conversion.
*
* @param price The price as a double (e.g., 12.50, 0.75, 123.456).
* @return The price in cents as a String (e.g., "1250", "75", "12346").
*/
public static String convertPriceToCentsString(double price) {
// 1. Create a BigDecimal from the double.
// It's crucial to create BigDecimal from its String representation
// to avoid potential floating-point inaccuracies that can occur
// when converting a double directly to BigDecimal.
// For example, 0.1 might be stored as 0.1000...0001 in double.
BigDecimal bd = new BigDecimal(String.valueOf(price));
// 2. Ensure exactly two decimal places and round appropriately.
// This is vital for prices. For example, 12.5 will become 12.50.
// 12.501 might become 12.50 (if rounding truncates/rounds down) or 12.51 (if rounds up).
// RoundingMode.HALF_UP is a common choice for commercial rounding (rounds .5 up).
bd = bd.setScale(2, RoundingMode.HALF_UP);
// 3. Multiply by 100 to shift the decimal two places to the right.
// e.g., 12.50 * 100 = 1250.00
BigDecimal multipliedPrice = bd.multiply(new BigDecimal("100"));
// 4. Convert the resulting BigDecimal to a long.
// longValueExact() will throw an ArithmeticException if the BigDecimal
// has a non-zero fractional part, which is good for validating that
// our multiplication resulted in an integer (e.g., 1250.00).
// If you are absolutely certain it will be an integer, longValue() is fine too.
long integerPriceInCents = multipliedPrice.longValueExact();
// 5. Convert the long to a String.
return String.valueOf(integerPriceInCents);
}
public static void main(String[] args) {
// Test cases
System.out.println("12.50 -> " + convertPriceToCentsString(12.50)); // Expected: 1250
System.out.println("12.00 -> " + convertPriceToCentsString(12.00)); // Expected: 1200
System.out.println("0.75 -> " + convertPriceToCentsString(0.75)); // Expected: 75
System.out.println("123.456 -> " + convertPriceToCentsString(123.456)); // Expected: 12346 (due to HALF_UP rounding of .456 to .46)
System.out.println("123.454 -> " + convertPriceToCentsString(123.454)); // Expected: 12345 (due to HALF_UP rounding of .454 to .45)
System.out.println("12.5 -> " + convertPriceToCentsString(12.5)); // Expected: 1250 (12.5 becomes 12.50)
System.out.println("0.0 -> " + convertPriceToCentsString(0.0)); // Expected: 0
System.out.println("-5.25 -> " + convertPriceToCentsString(-5.25)); // Expected: -525
System.out.println("10.005 -> " + convertPriceToCentsString(10.005)); // Expected: 1001 (due to HALF_UP rounding)
System.out.println("10.004 -> " + convertPriceToCentsString(10.004)); // Expected: 1000 (due to HALF_UP rounding)
}
}
Explanation:
new BigDecimal(String.valueOf(price)): This is crucial. Directly using new BigDecimal(double) can still suffer from the inherent precision issues of double if the double itself wasn't perfectly representable. By converting the double to its string representation first, you ensure that the BigDecimal is constructed from the exact decimal value you intend.
setScale(2, RoundingMode.HALF_UP):
setScale(2) ensures the number has exactly two decimal places.
RoundingMode.HALF_UP is a standard rounding mode for financial calculations. It means "round half up", where x.y5 rounds up to x.(y+1). For example, 12.345 becomes 12.35, and 12.344 becomes 12.34.
This step is important if your input double might have more than two decimal places (e.g., 12.501) or fewer (e.g., 12.5). It normalizes it to a standard price format.
multiply(new BigDecimal("100")): This multiplies the price by 100, effectively shifting the decimal point two places to the right (e.g., 12.50 becomes 1250.00).
longValueExact(): This method converts the BigDecimal to a long. It's a "checked" conversion, meaning it will throw an ArithmeticException if the BigDecimal has any non-zero fractional part after the multiplication (e.g., if it was 1250.01). Since we multiplied by 100 and set scale to 2, it should always be an exact integer, making this a safe and validating choice. If you just used longValue(), it would simply truncate any fractional part without error.
String.valueOf(integerPriceInCents): Finally, convert the long (which now represents the price in cents) to a String.
This BigDecimal approach is robust, precise, and highly recommended for any financial calculations in Java.