Skip to content

Instantly share code, notes, and snippets.

@wpsmith
Created July 4, 2021 00:01
Show Gist options
  • Save wpsmith/002d78085a83b98158b7bbceca9feba8 to your computer and use it in GitHub Desktop.
Save wpsmith/002d78085a83b98158b7bbceca9feba8 to your computer and use it in GitHub Desktop.
Java: Price Utility for Handling Pricing appropriately.
package wpsmith.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
/**
* Price Object.
*
* Price.parseDouble(myDouble).toString().
*/
public class Price {
/**
* Scale.
*/
protected static int SCALE = 0;
/**
* Rounding Mode.
*/
protected static RoundingMode ROUNDING_MODE = RoundingMode.HALF_UP;
/**
* Sets the scale for BigDecimal values.
*
* @param value Number of decimals.
*/
public static void setScale(int value) {
SCALE = value;
}
/**
* Set the scale and rounding method on Big Decimal.
*
* @param amount Amount to format.
* @return BigDecimal
*/
public static BigDecimal parseBigDecimal(BigDecimal amount) {
return amount.setScale(SCALE, ROUNDING_MODE);
}
/**
* Parses a float into a Big Decimal.
*
* @param amount Amount to format.
* @return BigDecimal
*/
public static BigDecimal parseFloat(Float amount) {
return parseBigDecimal(BigDecimal.valueOf(amount));
}
/**
* Parses a float into a Big Decimal.
*
* @param amount Amount to format.
* @return BigDecimal
*/
public static BigDecimal parseInt(int amount) {
return parseBigDecimal(BigDecimal.valueOf(amount));
}
/**
* Parses a float into a Big Decimal.
*
* @param amount Amount to format.
* @return BigDecimal
*/
public static BigDecimal parseDouble(double amount) {
return parseBigDecimal(BigDecimal.valueOf(amount));
}
/**
* Parses a string into a Big Decimal.
*
* @param amount Amount to format.
* @return BigDecimal
*/
public static BigDecimal parseString(String amount) {
return parseDouble(Double.parseDouble(amount));
}
/**
* Gets decimal value as string.
*
* @param value BigDecimal
* @return String
*/
public static String getBigDecimalAsString(BigDecimal value) {
value = Price.parseBigDecimal(value);
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(SCALE);
df.setMinimumFractionDigits(SCALE);
df.setGroupingUsed(false);
return df.format(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment