Created
July 4, 2021 00:01
-
-
Save wpsmith/002d78085a83b98158b7bbceca9feba8 to your computer and use it in GitHub Desktop.
Java: Price Utility for Handling Pricing appropriately.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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