Created
April 13, 2023 17:36
-
-
Save omernaci/6fe2b182d880c7fa240a0ed461083254 to your computer and use it in GitHub Desktop.
Java BigDecimal Best Practice
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
import java.math.BigDecimal; | |
import java.math.RoundingMode; | |
public class BigDecimalExample { | |
public static void main(String[] args) { | |
// Creating BigDecimal objects using the String constructor | |
BigDecimal value1 = new BigDecimal("123.456"); | |
BigDecimal value2 = new BigDecimal("123.4560"); | |
// Performing arithmetic operations with the HALF_UP rounding mode | |
BigDecimal result1 = value1.add(value2).setScale(2, RoundingMode.HALF_UP); | |
BigDecimal result2 = value2.subtract(value1).setScale(2, RoundingMode.HALF_UP); | |
BigDecimal result3 = value1.multiply(value2).setScale(2, RoundingMode.HALF_UP); | |
// Comparing values using the compareTo() method | |
if (value1.compareTo(value2) == 0) { | |
System.out.println("value1 is equal to value2"); | |
} else if (value1.compareTo(value2) < 0) { | |
System.out.println("value1 is less than value2"); | |
} else { | |
System.out.println("value1 is greater than value2"); | |
} | |
// Printing results | |
System.out.println("Result of value1 + value2: " + result1); | |
System.out.println("Result of value2 - value1: " + result2); | |
System.out.println("Result of value1 * value2: " + result3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment