修改项目到不同的路径
This commit is contained in:
+116
@@ -0,0 +1,116 @@
|
||||
package com.ossez.decimalformat;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DecimalFormatExamplesUnitTest {
|
||||
|
||||
double d = 1234567.89;
|
||||
|
||||
@Test
|
||||
public void givenSimpleDecimal_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("#########.###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("000000000.000", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("001234567.890");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSmallerDecimalPattern_WhenFormatting_ThenRounding() {
|
||||
|
||||
assertThat(new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234567.9");
|
||||
|
||||
assertThat(new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234568");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGroupingSeparator_WhenFormatting_ThenGroupedOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#,###.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,567.9");
|
||||
|
||||
assertThat(new DecimalFormat("#,###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,568");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMixedPattern_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("The # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("The 1234568 number");
|
||||
|
||||
assertThat(new DecimalFormat("The '#' # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("The # 1234568 number");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocales_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,567.89");
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ITALIAN)).format(d))
|
||||
.isEqualTo("1.234.567,89");
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(new Locale("it", "IT"))).format(d))
|
||||
.isEqualTo("1.234.567,89");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenE_WhenFormatting_ThenScientificNotation() {
|
||||
|
||||
assertThat(new DecimalFormat("00.#######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("12.3456789E5");
|
||||
|
||||
assertThat(new DecimalFormat("000.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("123.456789E4");
|
||||
|
||||
assertThat(new DecimalFormat("##0.######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1.23456789E6");
|
||||
|
||||
assertThat(new DecimalFormat("###.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1.23456789E6");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenParsing_ThenCorrectOutput() throws ParseException {
|
||||
|
||||
assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH)).parse("1234567.89"))
|
||||
.isEqualTo(1234567.89);
|
||||
|
||||
assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ITALIAN)).parse("1.234.567,89"))
|
||||
.isEqualTo(1234567.89);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndBigDecimalFlag_WhenParsing_ThenCorrectOutput() throws ParseException {
|
||||
|
||||
NumberFormat nf = new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH));
|
||||
((DecimalFormat) nf).setParseBigDecimal(true);
|
||||
assertThat(nf.parse("1234567.89")).isEqualTo(BigDecimal.valueOf(1234567.89));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package com.ossez.maths;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.math.MathContext;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Random;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.lang3.RandomUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class BigDecimalDemoUnitTest {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BigDecimalDemoUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenBigDecimalCreated_thenValueMatches() {
|
||||
BigDecimal bdFromString = new BigDecimal("0.1");
|
||||
BigDecimal bdFromCharArray = new BigDecimal(
|
||||
new char[]{'3', '.', '1', '6', '1', '5'});
|
||||
BigDecimal bdlFromInt = new BigDecimal(42);
|
||||
BigDecimal bdFromLong = new BigDecimal(123412345678901L);
|
||||
BigInteger bigInteger = BigInteger.probablePrime(100, new Random());
|
||||
BigDecimal bdFromBigInteger = new BigDecimal(bigInteger);
|
||||
|
||||
assertEquals("0.1", bdFromString.toString());
|
||||
assertEquals("3.1615", bdFromCharArray.toString());
|
||||
assertEquals("42", bdlFromInt.toString());
|
||||
assertEquals("123412345678901", bdFromLong.toString());
|
||||
assertEquals(bigInteger.toString(), bdFromBigInteger.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBigDecimalCreatedFromDouble_thenValueMayNotMatch() {
|
||||
BigDecimal bdFromDouble = new BigDecimal(0.1d);
|
||||
assertNotEquals("0.1", bdFromDouble.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBigDecimalCreatedUsingValueOf_thenValueMatches() {
|
||||
BigDecimal bdFromLong1 = BigDecimal.valueOf(123412345678901L);
|
||||
BigDecimal bdFromLong2 = BigDecimal.valueOf(123412345678901L, 2);
|
||||
BigDecimal bdFromDouble = BigDecimal.valueOf(0.1d);
|
||||
|
||||
assertEquals("123412345678901", bdFromLong1.toString());
|
||||
assertEquals("1234123456789.01", bdFromLong2.toString());
|
||||
assertEquals("0.1", bdFromDouble.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEqualsCalled_thenSizeAndScaleMatched() {
|
||||
BigDecimal bd1 = new BigDecimal("1.0");
|
||||
BigDecimal bd2 = new BigDecimal("1.00");
|
||||
|
||||
assertFalse(bd1.equals(bd2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingBigDecimals_thenExpectedResult() {
|
||||
BigDecimal bd1 = new BigDecimal("1.0");
|
||||
BigDecimal bd2 = new BigDecimal("1.00");
|
||||
BigDecimal bd3 = new BigDecimal("2.0");
|
||||
|
||||
assertTrue(bd1.compareTo(bd3) < 0);
|
||||
assertTrue(bd3.compareTo(bd1) > 0);
|
||||
assertTrue(bd1.compareTo(bd2) == 0);
|
||||
assertTrue(bd1.compareTo(bd3) <= 0);
|
||||
assertTrue(bd1.compareTo(bd2) >= 0);
|
||||
assertTrue(bd1.compareTo(bd3) != 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPerformingArithmetic_thenExpectedResult() {
|
||||
BigDecimal bd1 = new BigDecimal("4.0");
|
||||
BigDecimal bd2 = new BigDecimal("2.0");
|
||||
|
||||
BigDecimal sum = bd1.add(bd2);
|
||||
BigDecimal difference = bd1.subtract(bd2);
|
||||
BigDecimal quotient = bd1.divide(bd2);
|
||||
BigDecimal product = bd1.multiply(bd2);
|
||||
|
||||
assertTrue(sum.compareTo(new BigDecimal("6.0")) == 0);
|
||||
assertTrue(difference.compareTo(new BigDecimal("2.0")) == 0);
|
||||
assertTrue(quotient.compareTo(new BigDecimal("2.0")) == 0);
|
||||
assertTrue(product.compareTo(new BigDecimal("8.0")) == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingAttributes_thenExpectedResult() {
|
||||
BigDecimal bd = new BigDecimal("-12345.6789");
|
||||
|
||||
assertEquals(9, bd.precision());
|
||||
assertEquals(4, bd.scale());
|
||||
assertEquals(-1, bd.signum());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRoundingDecimal_thenExpectedResult() {
|
||||
BigDecimal bd = new BigDecimal("2.5");
|
||||
// Round to 1 digit using HALF_EVEN
|
||||
BigDecimal rounded = bd
|
||||
.round(new MathContext(1, RoundingMode.HALF_EVEN));
|
||||
|
||||
assertEquals("2", rounded.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPurchaseTxn_whenCalculatingTotalAmount_thenExpectedResult() {
|
||||
BigDecimal quantity = new BigDecimal("4.5");
|
||||
BigDecimal unitPrice = new BigDecimal("2.69");
|
||||
BigDecimal discountRate = new BigDecimal("0.10");
|
||||
BigDecimal taxRate = new BigDecimal("0.0725");
|
||||
|
||||
BigDecimal amountToBePaid = BigDecimalDemo
|
||||
.calculateTotalAmount(quantity, unitPrice, discountRate, taxRate);
|
||||
assertEquals("11.68", amountToBePaid.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* To String without ScientificNotation
|
||||
*/
|
||||
@Test
|
||||
public void bigDecimalWithoutScientificNotationTest() {
|
||||
String input = RandomStringUtils.randomNumeric(12)
|
||||
+ "12345678901234567"
|
||||
+ "8901234567890123"
|
||||
+ "4567890123456789"
|
||||
+ "0123456789012345"
|
||||
+ "6789012345678901"
|
||||
+ "2345678901234567"
|
||||
+ "8901234567890123"
|
||||
+ "4567890123456789"
|
||||
+ "0123456789012345"
|
||||
+ "6789012345678901"
|
||||
+ "2345678901234567"
|
||||
+ "8901234567890123"
|
||||
+ "4567890123456789"
|
||||
+ "0123456789012345"
|
||||
+ "6789012345678901"
|
||||
+ "2345678901234567"
|
||||
+ "8901234567890123"
|
||||
+ "4554324324362432"
|
||||
+ "7674637264783264"
|
||||
+ "7832678463726478"
|
||||
+ "3264736274673864"
|
||||
+ "7364732463546354"
|
||||
+ "6354632564532645"
|
||||
+ "6325463546536453"
|
||||
+ "6546325463546534"
|
||||
+ "6325465345326456"
|
||||
+ "4635463263453264";
|
||||
// Converting to BigDecimal
|
||||
BigDecimal bigNumber = new BigDecimal(input);
|
||||
|
||||
// Apply toString() method
|
||||
String numberStr = bigNumber.toString();
|
||||
|
||||
// Print the result
|
||||
logger.info("{}", numberStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* To String with ScientificNotation
|
||||
*/
|
||||
@Test
|
||||
public void bigDecimalScientificNotation() {
|
||||
// Create a BigDecimal object
|
||||
BigDecimal bigNumber;
|
||||
|
||||
// Create a String object
|
||||
String numberStr;
|
||||
|
||||
// Set precision to 5
|
||||
MathContext mc = new MathContext(6);
|
||||
|
||||
bigNumber = new BigDecimal(RandomStringUtils.randomNumeric(10) + "E5", mc);
|
||||
|
||||
// apply toString() method
|
||||
logger.info("{}", bigNumber.toString());
|
||||
logger.info("{}", bigNumber.toEngineeringString());
|
||||
logger.info("{}", bigNumber.toPlainString());
|
||||
}
|
||||
|
||||
/**
|
||||
* To StripTrailingZeros
|
||||
*/
|
||||
@Test
|
||||
public void bigDecimalStripTrailingZerosTest() {
|
||||
BigDecimal bigNumber = new BigDecimal("2707000000000");
|
||||
|
||||
// apply StripTrailingZeros function
|
||||
logger.info("{}", bigNumber.toString());
|
||||
logger.info("{}", bigNumber.stripTrailingZeros().toString());
|
||||
logger.info("{}", bigNumber.stripTrailingZeros().toPlainString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ossez.maths;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
public class BigDecimalImplUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||
BigDecimal serviceTax = new BigDecimal("56.0084578639");
|
||||
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
|
||||
|
||||
BigDecimal entertainmentTax = new BigDecimal("23.00689");
|
||||
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
|
||||
|
||||
BigDecimal totalTax = serviceTax.add(entertainmentTax);
|
||||
BigDecimal result = BigDecimal.valueOf(79.01);
|
||||
|
||||
Assert.assertEquals(result, totalTax);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.ossez.maths;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BigIntegerDemoUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenBigIntegerCreatedFromConstructor_thenExpectedResult() {
|
||||
BigInteger biFromString = new BigInteger("1234567890987654321");
|
||||
BigInteger biFromByteArray = new BigInteger(
|
||||
new byte[] { 64, 64, 64, 64, 64, 64 });
|
||||
BigInteger biFromSignMagnitude = new BigInteger(-1,
|
||||
new byte[] { 64, 64, 64, 64, 64, 64 });
|
||||
|
||||
assertEquals("1234567890987654321", biFromString.toString());
|
||||
assertEquals("70644700037184", biFromByteArray.toString());
|
||||
assertEquals("-70644700037184", biFromSignMagnitude.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLongConvertedToBigInteger_thenValueMatches() {
|
||||
BigInteger bi = BigInteger.valueOf(2305843009213693951L);
|
||||
|
||||
assertEquals("2305843009213693951", bi.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whentCompared_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("123456789012345678901234567890");
|
||||
BigInteger j = new BigInteger("123456789012345678901234567891");
|
||||
BigInteger k = new BigInteger("123456789012345678901234567892");
|
||||
|
||||
assertTrue(i.compareTo(i) == 0);
|
||||
assertTrue(j.compareTo(i) > 0);
|
||||
assertTrue(j.compareTo(k) < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenPerformingArithmetic_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("4");
|
||||
BigInteger j = new BigInteger("2");
|
||||
|
||||
BigInteger sum = i.add(j);
|
||||
BigInteger difference = i.subtract(j);
|
||||
BigInteger quotient = i.divide(j);
|
||||
BigInteger product = i.multiply(j);
|
||||
|
||||
assertEquals(new BigInteger("6"), sum);
|
||||
assertEquals(new BigInteger("2"), difference);
|
||||
assertEquals(new BigInteger("2"), quotient);
|
||||
assertEquals(new BigInteger("8"), product);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenPerformingBitOperations_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("17");
|
||||
BigInteger j = new BigInteger("7");
|
||||
|
||||
BigInteger and = i.and(j);
|
||||
BigInteger or = i.or(j);
|
||||
BigInteger not = j.not();
|
||||
BigInteger xor = i.xor(j);
|
||||
BigInteger andNot = i.andNot(j);
|
||||
BigInteger shiftLeft = i.shiftLeft(1);
|
||||
BigInteger shiftRight = i.shiftRight(1);
|
||||
|
||||
assertEquals(new BigInteger("1"), and);
|
||||
assertEquals(new BigInteger("23"), or);
|
||||
assertEquals(new BigInteger("-8"), not);
|
||||
assertEquals(new BigInteger("22"), xor);
|
||||
assertEquals(new BigInteger("16"), andNot);
|
||||
assertEquals(new BigInteger("34"), shiftLeft);
|
||||
assertEquals(new BigInteger("8"), shiftRight);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenPerformingBitManipulations_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("1018");
|
||||
|
||||
int bitCount = i.bitCount();
|
||||
int bitLength = i.bitLength();
|
||||
int getLowestSetBit = i.getLowestSetBit();
|
||||
boolean testBit3 = i.testBit(3);
|
||||
BigInteger setBit12 = i.setBit(12);
|
||||
BigInteger flipBit0 = i.flipBit(0);
|
||||
BigInteger clearBit3 = i.clearBit(3);
|
||||
|
||||
assertEquals(8, bitCount);
|
||||
assertEquals(10, bitLength);
|
||||
assertEquals(1, getLowestSetBit);
|
||||
assertEquals(true, testBit3);
|
||||
assertEquals(new BigInteger("5114"), setBit12);
|
||||
assertEquals(new BigInteger("1019"), flipBit0);
|
||||
assertEquals(new BigInteger("1010"), clearBit3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenModularCalculation_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("31");
|
||||
BigInteger j = new BigInteger("24");
|
||||
BigInteger k = new BigInteger("16");
|
||||
|
||||
BigInteger gcd = j.gcd(k);
|
||||
BigInteger multiplyAndmod = j.multiply(k)
|
||||
.mod(i);
|
||||
BigInteger modInverse = j.modInverse(i);
|
||||
BigInteger modPow = j.modPow(k, i);
|
||||
|
||||
assertEquals(new BigInteger("8"), gcd);
|
||||
assertEquals(new BigInteger("12"), multiplyAndmod);
|
||||
assertEquals(new BigInteger("22"), modInverse);
|
||||
assertEquals(new BigInteger("7"), modPow);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenPrimeOperations_thenExpectedResult() {
|
||||
BigInteger i = BigInteger.probablePrime(100, new Random());
|
||||
|
||||
boolean isProbablePrime = i.isProbablePrime(1000);
|
||||
assertEquals(true, isProbablePrime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ossez.maths;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerImplUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
|
||||
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
|
||||
|
||||
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
|
||||
BigInteger result = new BigInteger("14110718640342675608722521633212952");
|
||||
|
||||
Assert.assertEquals(result, totalStars);
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.ossez.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FloatingPointArithmeticUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||
double a = 13.22;
|
||||
double b = 4.88;
|
||||
double c = 21.45;
|
||||
double result = 39.55;
|
||||
|
||||
double abc = a + b + c;
|
||||
double acb = a + c + b;
|
||||
|
||||
Assert.assertEquals(result, abc, 0);
|
||||
Assert.assertNotEquals(result, acb, 0);
|
||||
|
||||
double ab = 18.1;
|
||||
double ac = 34.67;
|
||||
|
||||
double ab_c = ab + c;
|
||||
double ac_b = ac + b;
|
||||
|
||||
Assert.assertEquals(result, ab_c, 0);
|
||||
Assert.assertNotEquals(result, ac_b, 0);
|
||||
|
||||
BigDecimal d = new BigDecimal(String.valueOf(a));
|
||||
BigDecimal e = new BigDecimal(String.valueOf(b));
|
||||
BigDecimal f = new BigDecimal(String.valueOf(c));
|
||||
BigDecimal sum = new BigDecimal("39.55");
|
||||
|
||||
BigDecimal def = d.add(e).add(f);
|
||||
BigDecimal dfe = d.add(f).add(e);
|
||||
|
||||
Assert.assertEquals(0, def.compareTo(sum));
|
||||
Assert.assertEquals(0, dfe.compareTo(sum));
|
||||
|
||||
Assert.assertNotEquals(0, sum.compareTo(new BigDecimal(String.valueOf(acb))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ossez.maths;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class MathSinUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnAngleInDegrees_whenUsingToRadians_thenResultIsInRadians() {
|
||||
double angleInDegrees = 30;
|
||||
double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5
|
||||
|
||||
double thirtyDegreesInRadians = (double) 1 / 6 * Math.PI;
|
||||
double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5
|
||||
|
||||
assertThat(sinForDegrees, is(sinForRadians));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ossez.maths;
|
||||
|
||||
import org.apache.commons.math3.util.Precision;
|
||||
import org.decimal4j.util.DoubleRounder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUnitTest {
|
||||
private double value = 2.03456d;
|
||||
private int places = 2;
|
||||
private double delta = 0.0d;
|
||||
private double expected = 2.03d;
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
|
||||
|
||||
places = 3;
|
||||
expected = 2.035d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
|
||||
|
||||
value = 1000.0d;
|
||||
places = 17;
|
||||
expected = 1000.0d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
|
||||
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 !
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
|
||||
|
||||
value = 256.025d;
|
||||
places = 2;
|
||||
expected = 256.03d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 !
|
||||
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 !
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 !
|
||||
|
||||
value = 260.775d;
|
||||
places = 2;
|
||||
expected = 260.78d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 !
|
||||
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 !
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 !
|
||||
|
||||
value = 90080070060.1d;
|
||||
places = 9;
|
||||
expected = 90080070060.1d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
|
||||
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 !
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.ossez.nth.root.calculator;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
public class NthRootCalculatorUnitTest {
|
||||
|
||||
private NthRootCalculator nthRootCalculator = new NthRootCalculator();
|
||||
|
||||
@Test
|
||||
public void whenBaseIs125AndNIs3_thenNthRootIs5() {
|
||||
Double result = nthRootCalculator.calculate(125.0, 3.0);
|
||||
assertEquals(result, (Double) 5.0d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ossez.nth.root.main;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MainUnitTest {
|
||||
@InjectMocks
|
||||
private Main main;
|
||||
|
||||
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||
private final PrintStream originalOut = System.out;
|
||||
|
||||
@Before
|
||||
public void setUpStreams() {
|
||||
System.setOut(new PrintStream(outContent));
|
||||
}
|
||||
|
||||
@After
|
||||
public void restoreStreams() {
|
||||
System.setOut(originalOut);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThatTheBaseIs125_andTheExpIs3_whenMainIsCalled_thenTheCorrectResultIsPrinted() {
|
||||
main.main(new String[]{"125.0", "3.0"});
|
||||
assertEquals("The 3.0 root of 125.0 equals to 5.0.\n", outContent.toString().replaceAll("\r", ""));
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.ossez.numberofdigits;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Assume;
|
||||
import org.junit.experimental.theories.DataPoints;
|
||||
import org.junit.experimental.theories.Theories;
|
||||
import org.junit.experimental.theories.Theory;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
@RunWith(Theories.class)
|
||||
public class NumberOfDigitsIntegrationTest {
|
||||
|
||||
private static NumberOfDigits numberOfDigits;
|
||||
|
||||
static {
|
||||
numberOfDigits = new NumberOfDigits();
|
||||
}
|
||||
|
||||
@DataPoints
|
||||
public static int[][] lowestIntegers()
|
||||
{
|
||||
return new int[][]{
|
||||
{1, 1},
|
||||
{2, 10},
|
||||
{3, 100},
|
||||
{4, 1000},
|
||||
{5, 10000},
|
||||
{6, 100000},
|
||||
{7, 1000000},
|
||||
{8, 10000000},
|
||||
{9, 100000000},
|
||||
{10, 1000000000}
|
||||
};
|
||||
}
|
||||
|
||||
@DataPoints
|
||||
public static int[][] highestIntegers()
|
||||
{
|
||||
return new int[][]{
|
||||
{1, 9},
|
||||
{2, 99},
|
||||
{3, 999},
|
||||
{4, 9999},
|
||||
{5, 99999},
|
||||
{6, 999999},
|
||||
{7, 9999999},
|
||||
{8, 99999999},
|
||||
{9, 999999999},
|
||||
{10, Integer.MAX_VALUE}
|
||||
};
|
||||
}
|
||||
|
||||
@DataPoints
|
||||
public static int[][] randomIntegers()
|
||||
{
|
||||
return new int[][]{
|
||||
{1, 1},
|
||||
{2, 14},
|
||||
{3, 549},
|
||||
{4, 1136},
|
||||
{5, 25340},
|
||||
{6, 134321},
|
||||
{7, 1435432},
|
||||
{8, 54234129},
|
||||
{9, 113683912},
|
||||
{10, 1534031982}
|
||||
};
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenStringBasedSolutionInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.stringBasedSolution(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenLogarithmicApproachInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.logarithmicApproach(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenRepeatedMultiplicationInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.repeatedMultiplication(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenShiftOperatorsInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.shiftOperators(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenDividingWithPowersOf2Invoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.dividingWithPowersOf2(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenDivideAndConquerInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.divideAndConquer(entry[1]));
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.ossez.pairsaddupnumber;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class DifferentPairsUnitTest {
|
||||
|
||||
/* All different pairs */
|
||||
|
||||
@Test
|
||||
public void whenTraditionalLoop_thenReturnAllDifferentPairs() {
|
||||
/* Data */
|
||||
final int[] input = {2, 4, 3, 3, 8};
|
||||
final int sum = 6;
|
||||
/* Call service */
|
||||
final List<Integer> pairs = DifferentPairs.findPairsWithForLoop(input, sum);
|
||||
/* Check results */
|
||||
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStreamApi_thenReturnAllDifferentPairs() {
|
||||
/* Data */
|
||||
final int[] input = {2, 4, 3, 3, 8};
|
||||
final int sum = 6;
|
||||
/* Call service */
|
||||
final List<Integer> pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
|
||||
/* Check results */
|
||||
assertNotNull(pairs);
|
||||
assertEquals(pairs.size(),2);
|
||||
assertEquals(pairs.get(0), new Integer(4));
|
||||
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.ossez.pairsaddupnumber;
|
||||
|
||||
import org.junit.Test;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class ExistingPairsUnitTest {
|
||||
|
||||
/* All existing pairs */
|
||||
|
||||
@Test
|
||||
public void whenTraditionalLoop_thenReturnAllExistingPairs() {
|
||||
/* Data */
|
||||
final int[] input = {2, 4, 3, 3, 8};
|
||||
final int sum = 6;
|
||||
/* Call service */
|
||||
final List<Integer> pairs = ExistingPairs.findPairsWithForLoop(input, sum);
|
||||
/* Check results */
|
||||
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStreamApi_thenReturnAllExistingPairs() {
|
||||
/* Data */
|
||||
final int[] input = {2, 4, 3, 3, 8};
|
||||
final int sum = 6;
|
||||
/* Call service */
|
||||
final List<Integer> pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
|
||||
/* Check results */
|
||||
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.ossez.random;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.math3.random.RandomDataGenerator;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class JavaRandomUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
|
||||
|
||||
// tests - random long
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() {
|
||||
final long generatedLong = new Random().nextLong();
|
||||
|
||||
LOG.debug("{}", generatedLong);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
|
||||
final long generatedLong = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextLong();
|
||||
|
||||
LOG.debug("{}", generatedLong);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomLongBounded_thenCorrect() {
|
||||
final long leftLimit = 1L;
|
||||
final long rightLimit = 10L;
|
||||
final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit));
|
||||
|
||||
LOG.debug("{}", generatedLong);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApacheCommons_whenGeneratingRandomLongBounded_thenCorrect() {
|
||||
final long leftLimit = 10L;
|
||||
final long rightLimit = 100L;
|
||||
final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit);
|
||||
|
||||
LOG.debug("{}", generatedLong);
|
||||
}
|
||||
|
||||
// tests - random int
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
|
||||
final int generatedInteger = new Random().nextInt();
|
||||
|
||||
LOG.debug("{}", generatedInteger);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomIntegerBounded_thenCorrect() {
|
||||
final int leftLimit = 1;
|
||||
final int rightLimit = 10;
|
||||
final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
|
||||
|
||||
LOG.debug("{}", generatedInteger);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
|
||||
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextInt();
|
||||
|
||||
LOG.debug("{}", generatedInteger);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomIntegerBounded_thenCorrect() {
|
||||
final int leftLimit = 1;
|
||||
final int rightLimit = 10;
|
||||
final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit);
|
||||
|
||||
LOG.debug("{}", generatedInteger);
|
||||
}
|
||||
|
||||
// tests - random float
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() {
|
||||
final float generatedFloat = new Random().nextFloat();
|
||||
|
||||
LOG.debug("{}", generatedFloat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
|
||||
final float generatedFloat = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextFloat();
|
||||
|
||||
LOG.debug("{}", generatedFloat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomFloatBouned_thenCorrect() {
|
||||
final float leftLimit = 1F;
|
||||
final float rightLimit = 10F;
|
||||
final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit);
|
||||
|
||||
LOG.debug("{}", generatedFloat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
|
||||
final float leftLimit = 1F;
|
||||
final float rightLimit = 10F;
|
||||
final float randomFloat = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextFloat();
|
||||
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
|
||||
|
||||
LOG.debug("{}", generatedFloat);
|
||||
}
|
||||
|
||||
// tests - random double
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
|
||||
final double generatedDouble = Math.random();
|
||||
|
||||
LOG.debug("{}", generatedDouble);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
|
||||
final double generatedDouble = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextDouble();
|
||||
|
||||
LOG.debug("{}", generatedDouble);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomDoubleBounded_thenCorrect() {
|
||||
final double leftLimit = 1D;
|
||||
final double rightLimit = 10D;
|
||||
final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit);
|
||||
|
||||
LOG.debug("{}", generatedDouble);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomDoubleBounded_thenCorrect() {
|
||||
final double leftLimit = 1D;
|
||||
final double rightLimit = 100D;
|
||||
final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit);
|
||||
|
||||
LOG.debug("{}", generatedDouble);
|
||||
}
|
||||
|
||||
// tests - random String
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
|
||||
final byte[] array = new byte[7]; // length is bounded by 7
|
||||
new Random().nextBytes(array);
|
||||
final String generatedString = new String(array, Charset.forName("UTF-8"));
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
final int leftLimit = 97; // letter 'a'
|
||||
final int rightLimit = 122; // letter 'z'
|
||||
final int targetStringLength = 10;
|
||||
final Random random = new Random();
|
||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
final String generatedString = buffer.toString();
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.random(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.randomAlphabetic(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.randomAlphanumeric(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
final int length = 10;
|
||||
final boolean useLetters = true;
|
||||
final boolean useNumbers = false;
|
||||
final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.ossez.removingdecimals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* This benchmark compares some of the approaches to formatting a floating-point
|
||||
* value into a {@link String} while removing the decimal part.
|
||||
*
|
||||
* To run, simply run the {@link RemovingDecimalsManualTest#runBenchmarks()} test
|
||||
* at the end of this class.
|
||||
*
|
||||
* The benchmark takes about 15 minutes to run. Since it is using {@link Mode#Throughput},
|
||||
* higher numbers mean better performance.
|
||||
*/
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 20)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@State(Scope.Benchmark)
|
||||
public class RemovingDecimalsManualTest {
|
||||
@Param(value = {"345.56", "345345345.56", "345345345345345345.56"}) double doubleValue;
|
||||
|
||||
NumberFormat nf;
|
||||
DecimalFormat df;
|
||||
|
||||
@Setup
|
||||
public void readyFormatters() {
|
||||
nf = NumberFormat.getInstance();
|
||||
nf.setMaximumFractionDigits(0);
|
||||
df = new DecimalFormat("#,###");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenCastToInt_thenValueIsTruncated() {
|
||||
return String.valueOf((int) doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingStringFormat_thenValueIsRounded() {
|
||||
return String.format("%.0f", doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingNumberFormat_thenValueIsRounded() {
|
||||
nf.setRoundingMode(RoundingMode.HALF_UP);
|
||||
return nf.format(doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
|
||||
nf.setRoundingMode(RoundingMode.FLOOR);
|
||||
return nf.format(doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingDecimalFormat_thenValueIsRounded() {
|
||||
df.setRoundingMode(RoundingMode.HALF_UP);
|
||||
return df.format(doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
|
||||
df.setRoundingMode(RoundingMode.FLOOR);
|
||||
return df.format(doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
|
||||
BigDecimal big = new BigDecimal(doubleValue);
|
||||
big = big.setScale(0, RoundingMode.FLOOR);
|
||||
return big.toString();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() {
|
||||
BigDecimal big = new BigDecimal(doubleValue);
|
||||
big = big.setScale(0, RoundingMode.HALF_UP);
|
||||
return big.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runBenchmarks() throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(this.getClass().getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package com.ossez.removingdecimals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
/**
|
||||
* Tests that demonstrate some different approaches for formatting a
|
||||
* floating-point value into a {@link String} while removing the decimal part.
|
||||
*/
|
||||
public class RemovingDecimalsUnitTest {
|
||||
private final double doubleValue = 345.56;
|
||||
|
||||
@Test
|
||||
public void whenCastToInt_thenValueIsTruncated() {
|
||||
String truncated = String.valueOf((int) doubleValue);
|
||||
assertEquals("345", truncated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALargeDouble_whenCastToInt_thenValueIsNotTruncated() {
|
||||
double outOfIntRange = 6_000_000_000.56;
|
||||
String truncationAttempt = String.valueOf((int) outOfIntRange);
|
||||
assertNotEquals("6000000000", truncationAttempt);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringFormat_thenValueIsRounded() {
|
||||
String rounded = String.format("%.0f", doubleValue);
|
||||
assertEquals("346", rounded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALargeDouble_whenUsingStringFormat_thenValueIsStillRounded() {
|
||||
double outOfIntRange = 6_000_000_000.56;
|
||||
String rounded = String.format("%.0f", outOfIntRange);
|
||||
assertEquals("6000000001", rounded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingNumberFormat_thenValueIsRounded() {
|
||||
NumberFormat nf = NumberFormat.getInstance();
|
||||
nf.setMaximumFractionDigits(0);
|
||||
nf.setRoundingMode(RoundingMode.HALF_UP);
|
||||
String rounded = nf.format(doubleValue);
|
||||
assertEquals("346", rounded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
|
||||
NumberFormat nf = NumberFormat.getInstance();
|
||||
nf.setMaximumFractionDigits(0);
|
||||
nf.setRoundingMode(RoundingMode.FLOOR);
|
||||
String truncated = nf.format(doubleValue);
|
||||
assertEquals("345", truncated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingDecimalFormat_thenValueIsRounded() {
|
||||
DecimalFormat df = new DecimalFormat("#,###");
|
||||
df.setRoundingMode(RoundingMode.HALF_UP);
|
||||
String rounded = df.format(doubleValue);
|
||||
assertEquals("346", rounded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
|
||||
DecimalFormat df = new DecimalFormat("#,###");
|
||||
df.setRoundingMode(RoundingMode.FLOOR);
|
||||
String truncated = df.format(doubleValue);
|
||||
assertEquals("345", truncated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
|
||||
BigDecimal big = new BigDecimal(doubleValue);
|
||||
big = big.setScale(0, RoundingMode.FLOOR);
|
||||
String truncated = big.toString();
|
||||
assertEquals("345", truncated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() {
|
||||
BigDecimal big = new BigDecimal(doubleValue);
|
||||
big = big.setScale(0, RoundingMode.HALF_UP);
|
||||
String truncated = big.toString();
|
||||
assertEquals("346", truncated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.ossez.string;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DoubleToStringUnitTest {
|
||||
|
||||
private static final double DOUBLE_VALUE = 3.56;
|
||||
private static final String TRUNCATED_DOUBLE = "3";
|
||||
private static final String ROUNDED_UP_DOUBLE = "4";
|
||||
|
||||
|
||||
@Test
|
||||
public void truncateByCastTest() {
|
||||
assertThat(DoubleToString.truncateByCast(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roundingWithStringFormatTest() {
|
||||
assertThat(DoubleToString.roundWithStringFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void truncateWithNumberFormatTest() {
|
||||
assertThat(DoubleToString.truncateWithNumberFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roundWithNumberFormatTest() {
|
||||
assertThat(DoubleToString.roundWithNumberFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void truncateWithDecimalFormatTest() {
|
||||
assertThat(DoubleToString.truncateWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roundWithDecimalFormatTest() {
|
||||
assertThat(DoubleToString.roundWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user