Java Examples for java.math.RoundingMode
The following java examples will help you to understand the usage of java.math.RoundingMode. These source code samples are taken from different open source projects.
Example 1
| Project: jtwig-master File: IntegerMultiplyOperationCalculatorTest.java View source code |
@Test
public void calculate() throws Exception {
RoundingMode roundingMode = RoundingMode.CEILING;
RenderRequest request = mock(RenderRequest.class, RETURNS_DEEP_STUBS);
BigDecimal left = mock(BigDecimal.class);
BigDecimal right = mock(BigDecimal.class);
BigDecimal leftRounded = mock(BigDecimal.class);
BigDecimal rightRounded = mock(BigDecimal.class);
BigDecimal expected = mock(BigDecimal.class);
when(request.getEnvironment().getValueEnvironment().getRoundingMode()).thenReturn(roundingMode);
when(left.setScale(0, roundingMode)).thenReturn(leftRounded);
when(right.setScale(0, roundingMode)).thenReturn(rightRounded);
when(leftRounded.multiply(rightRounded)).thenReturn(expected);
BigDecimal result = underTest.calculate(request, left, right);
assertEquals(expected, result);
}Example 2
| Project: intellij-community-master File: BigDecimalLegacyMethodInspection.java View source code |
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
final PsiElement grandParent = element.getParent().getParent();
if (!(grandParent instanceof PsiMethodCallExpression)) {
return;
}
final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) grandParent;
final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
final PsiExpression[] arguments = argumentList.getExpressions();
if (arguments.length != 2 && arguments.length != 3) {
return;
}
final PsiExpression argument = arguments[arguments.length - 1];
final Object value = ExpressionUtils.computeConstantExpression(argument);
if (!(value instanceof Integer)) {
return;
}
final int roundingMode = (Integer) value;
switch(roundingMode) {
case 0:
PsiReplacementUtil.replaceExpressionAndShorten(argument, "java.math.RoundingMode.UP");
break;
case 1:
PsiReplacementUtil.replaceExpressionAndShorten(argument, "java.math.RoundingMode.DOWN");
break;
case 2:
PsiReplacementUtil.replaceExpressionAndShorten(argument, "java.math.RoundingMode.CEILING");
break;
case 3:
PsiReplacementUtil.replaceExpressionAndShorten(argument, "java.math.RoundingMode.FLOOR");
break;
case 4:
PsiReplacementUtil.replaceExpressionAndShorten(argument, "java.math.RoundingMode.HALF_UP");
break;
case 5:
PsiReplacementUtil.replaceExpressionAndShorten(argument, "java.math.RoundingMode.HALF_DOWN");
break;
case 6:
PsiReplacementUtil.replaceExpressionAndShorten(argument, "java.math.RoundingMode.HALF_EVEN");
break;
case 7:
PsiReplacementUtil.replaceExpressionAndShorten(argument, "java.math.RoundingMode.UNNECESSARY");
break;
}
}Example 3
| Project: h2o-3-master File: AstSignif.java View source code |
public double op(double x, double digits) {
if (Double.isNaN(x))
return x;
//mimic R's base::signif
if (digits < 1)
digits = 1;
if ((int) digits != digits)
digits = Math.round(digits);
java.math.BigDecimal bd = new java.math.BigDecimal(x);
bd = bd.round(new java.math.MathContext((int) digits, java.math.RoundingMode.HALF_EVEN));
return bd.doubleValue();
}Example 4
| Project: mekhq-master File: BigDecimalAssert.java View source code |
public static void assertEquals(BigDecimal expected, Object actual, int scale) {
TestCase.assertNotNull(actual);
TestCase.assertTrue("actual: " + actual.getClass().getName(), actual instanceof BigDecimal);
BigDecimal scaledExpected = expected.setScale(scale, RoundingMode.FLOOR);
BigDecimal scaledActual = ((BigDecimal) actual).setScale(scale, RoundingMode.FLOOR);
TestCase.assertTrue("\n\texpected: " + scaledExpected + "\n\tactual: " + scaledActual, scaledExpected.compareTo(scaledActual) == 0);
}Example 5
| Project: thunderstorm-master File: StringFormatting.java View source code |
public static DecimalFormat getDecimalFormat(int floatPrecision) {
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.US);
symbols.setInfinity("Infinity");
symbols.setNaN("NaN");
df.setDecimalFormatSymbols(symbols);
df.setGroupingUsed(false);
df.setRoundingMode(RoundingMode.HALF_EVEN);
df.setMaximumFractionDigits(floatPrecision);
return df;
}Example 6
| Project: cloudconductor-server-master File: ByteTool.java View source code |
/**
* @param bytes the bytes
* @return the formated string
*/
public String format(long bytes) {
BigDecimal byteCount = new BigDecimal(bytes).setScale(3, RoundingMode.HALF_UP);
int thousandStep = 0;
while (byteCount.longValue() > 1024) {
byteCount = byteCount.divide(new BigDecimal("1024"), 3, RoundingMode.HALF_UP);
thousandStep++;
}
return byteCount.toPlainString() + " " + this.getUnit(thousandStep);
}Example 7
| Project: janusproject-master File: BigIntegerMath.java View source code |
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static // TODO(kevinb): remove after this warning is disabled globally
int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch(mode) {
case UNNECESSARY:
// fall through
checkRoundingUnnecessary(isPowerOfTwo(x));
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
/*
* Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
*
* To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 *
* logFloor + 1).
*/
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}Example 8
| Project: BikeMan-master File: Ticket3000Impl.java View source code |
@Override
public BigDecimal calculate(Transaction transaction) {
Duration duration = new Duration(transaction.getStartDateTime().toDateTime(DateTimeZone.UTC), transaction.getEndDateTime().toDateTime(DateTimeZone.UTC));
BigDecimal durationInMin = new BigDecimal(duration.getStandardMinutes());
if (durationInMin.compareTo(freeTimeInMin) != 1) {
return BigDecimal.ZERO;
}
return durationInMin.subtract(freeTimeInMin).divide(timeUnitInMin, 0, RoundingMode.CEILING).multiply(pricePerTimeUnit);
}Example 9
| Project: bonaparte-java-master File: TestBigDecimalValidation.java View source code |
@Test
public void testBigDecimal() throws Exception {
Set<ConstraintViolation<BDTest>> violations;
BDTest bd = new BDTest(new BigDecimal("3.14"));
System.out.println("Scale is " + bd.getAmount().scale() + ", precision is " + bd.getAmount().precision());
violations = validator.validate(bd);
assert violations.size() == 0 : "Issue with BigDecimal";
bd = new BDTest(new BigDecimal("3.14000000"));
System.out.println("Scale is " + bd.getAmount().scale() + ", precision is " + bd.getAmount().precision());
bd.setAmount(bd.getAmount().setScale(6, RoundingMode.UNNECESSARY));
System.out.println("New Scale is " + bd.getAmount().scale() + ", precision is " + bd.getAmount().precision() + ", value is " + bd.getAmount().toString());
violations = validator.validate(bd);
assert violations.size() == 0 : "Issue with BigDecimal";
}Example 10
| Project: coding2017-master File: Math.java View source code |
@SuppressWarnings("unchecked")
public static double div(double left, double right, int scale) throws IllegalAccessException {
// 如果精确范围�于0,抛出异常信�
if (scale < 0) {
throw new IllegalAccessException("精确度�能�于0");
}
BigDecimal divisor = new BigDecimal(left);
BigDecimal dividend = new BigDecimal(right);
return divisor.divide(dividend, scale, RoundingMode.HALF_EVEN).doubleValue();
}Example 11
| Project: contribution_eevolution_costing_engine-master File: CostComponent.java View source code |
public BigDecimal getAmount() {
BigDecimal amt = qty.multiply(priceActual);
if (this.percent.signum() != 0) {
amt = amt.multiply(this.percent);
amt = amt.divide(Env.ONEHUNDRED, this.scale, RoundingMode.HALF_UP);
}
if (amt.scale() > this.scale) {
amt = amt.setScale(this.scale, RoundingMode.HALF_UP);
}
return amt;
}Example 12
| Project: geosummly-master File: SSEValidation.java View source code |
public static void main(String[] args) {
try {
StringBuilder sb = new StringBuilder();
sb.append("x=c(");
List<String> lines = FileUtils.readLines(new File("datasets/milan/20140328/validation/clustering_correctness/SSEs.log"));
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(4);
nf.setMinimumFractionDigits(4);
nf.setRoundingMode(RoundingMode.HALF_UP);
for (int i = 0; i < lines.size(); i++) {
String[] chunks = lines.get(i).split(",");
//sb.append( nf.format(Double.parseDouble(chunks[1])) );
sb.append((int) Math.floor(Double.parseDouble(chunks[1])));
if (i < lines.size() - 1)
sb.append(", ");
}
sb.append(");\n");
sb.append("bins=seq(2060,2512,by=0.5);\n");
sb.append("hist(x," + "breaks=bins," + "xlab=\"SSE\",ylab=\"count\"," + "main=\"Histogram of SSE for 500 random data sets\")");
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}Example 13
| Project: Mint-Programming-Language-master File: Div.java View source code |
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
Pointer arg0 = args.get(0);
Pointer arg1 = args.get(1);
if ((arg0.type == Constants.BIG_INT_TYPE && arg1.type == Constants.BIG_INT_TYPE) || (arg0.type == Constants.PRECISE_REAL_TYPE && arg1.type == Constants.PRECISE_REAL_TYPE)) {
BigDecimal bd0 = PointerTools.dereferencePreciseReal(arg0);
BigDecimal bd1 = PointerTools.dereferencePreciseReal(arg1);
return Heap.allocatePreciseReal(bd0.divide(bd1, 200, RoundingMode.HALF_UP));
}
Double operand0 = PointerTools.dereferenceReal(arg0);
Double operand1 = PointerTools.dereferenceReal(arg1);
if (arg0 == null || arg1 == null) {
throw new MintException("Divide can only be applied to " + "integers or reals.");
}
return Heap.allocateReal(operand0 / operand1);
}Example 14
| Project: MintChime-Editor-master File: Div.java View source code |
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
Pointer arg0 = args.get(0);
Pointer arg1 = args.get(1);
if ((arg0.type == Constants.BIG_INT_TYPE && arg1.type == Constants.BIG_INT_TYPE) || (arg0.type == Constants.PRECISE_REAL_TYPE && arg1.type == Constants.PRECISE_REAL_TYPE)) {
BigDecimal bd0 = PointerTools.dereferencePreciseReal(arg0);
BigDecimal bd1 = PointerTools.dereferencePreciseReal(arg1);
return Heap.allocatePreciseReal(bd0.divide(bd1, 200, RoundingMode.HALF_UP));
}
Double operand0 = PointerTools.dereferenceReal(arg0);
Double operand1 = PointerTools.dereferenceReal(arg1);
if (arg0 == null || arg1 == null) {
throw new MintException("Divide can only be applied to " + "integers or reals.");
}
return Heap.allocateReal(operand0 / operand1);
}Example 15
| Project: OG-Platform-master File: EnumUtilsTest.java View source code |
//-------------------------------------------------------------------------
public void test_safeValueOf() {
assertEquals(RoundingMode.FLOOR, EnumUtils.safeValueOf(RoundingMode.class, "FLOOR"));
assertEquals(null, EnumUtils.safeValueOf(RoundingMode.class, null));
assertEquals(null, EnumUtils.<RoundingMode>safeValueOf(null, "FLOOR"));
assertEquals(null, EnumUtils.safeValueOf(RoundingMode.class, "RUBBISH"));
}Example 16
| Project: poseidon-rest-master File: DPOrderMapper.java View source code |
private DPOrder mapToApi(OrderModel mOrder) {
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.HALF_UP);
DPOrder dpOrder = new DPOrder();
dpOrder.id = mOrder.id;
String posname = mOrder.position.name;
String name = mOrder.position_name != null & !mOrder.position_name.isEmpty() ? mOrder.position_name : mOrder.position.name;
try {
dpOrder.name = URLEncoder.encode(name, "UTF-8");
dpOrder.posname = URLEncoder.encode(posname, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
dpOrder.name_dec = name;
dpOrder.longitude = mOrder.position.longitude;
dpOrder.latitude = mOrder.position.latitude;
return dpOrder;
}Example 17
| Project: ProtectPlugin-master File: TickManager.java View source code |
public void run() {
BigDecimal tick = new BigDecimal("1200");
BigDecimal per = new BigDecimal(System.currentTimeMillis() - getLast());
BigDecimal second = per.divide(new BigDecimal("1000"), 4, RoundingMode.HALF_UP);
double tps = tick.divide(second, 2, RoundingMode.HALF_UP).doubleValue();
List<Double> recent = getTps();
recent.add(0, tps > 20 ? 20 : tps);
if (recent.size() > 3) {
recent.remove(3);
}
setLast(System.currentTimeMillis());
}Example 18
| Project: urlaubsverwaltung-master File: DecimalNumberPropertyEditor.java View source code |
@Override
public String getAsText() {
if (this.getValue() == null) {
return "";
}
try {
BigDecimal number = (BigDecimal) this.getValue();
NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
numberFormat.setMaximumFractionDigits(2);
return numberFormat.format(number.setScale(2, RoundingMode.HALF_UP).doubleValue());
} catch (ClassCastException ex) {
throw new IllegalArgumentException("The provided value is of invalid type", ex);
}
}Example 19
| Project: android-libcore64-master File: MathContextTest.java View source code |
/**
* java.math.MathContext#MathContext(...)
*/
public void test_MathContextConstruction() {
String a = "-12380945E+61";
BigDecimal aNumber = new BigDecimal(a);
MathContext mcIntRm6hd = new MathContext(6, RoundingMode.HALF_DOWN);
MathContext mcStr6hd = new MathContext("precision=6 roundingMode=HALF_DOWN");
MathContext mcInt6 = new MathContext(6);
MathContext mcInt134 = new MathContext(134);
// getPrecision()
assertEquals("MathContext.getPrecision() returns incorrect value", 6, mcIntRm6hd.getPrecision());
assertEquals("MathContext.getPrecision() returns incorrect value", 134, mcInt134.getPrecision());
// getRoundingMode()
assertEquals("MathContext.getRoundingMode() returns incorrect value", RoundingMode.HALF_UP, mcInt6.getRoundingMode());
assertEquals("MathContext.getRoundingMode() returns incorrect value", RoundingMode.HALF_DOWN, mcIntRm6hd.getRoundingMode());
// toString()
assertEquals("MathContext.toString() returning incorrect value", "precision=6 roundingMode=HALF_DOWN", mcIntRm6hd.toString());
assertEquals("MathContext.toString() returning incorrect value", "precision=6 roundingMode=HALF_UP", mcInt6.toString());
// equals(.)
assertEquals("Equal MathContexts are not equal ", mcIntRm6hd, mcStr6hd);
assertFalse("Different MathContexts are reported as equal ", mcInt6.equals(mcStr6hd));
assertFalse("Different MathContexts are reported as equal ", mcInt6.equals(mcInt134));
// hashCode(.)
assertEquals("Equal MathContexts have different hashcodes ", mcIntRm6hd.hashCode(), mcStr6hd.hashCode());
assertFalse("Different MathContexts have equal hashcodes ", mcInt6.hashCode() == mcStr6hd.hashCode());
assertFalse("Different MathContexts have equal hashcodes ", mcInt6.hashCode() == mcInt134.hashCode());
// other:
BigDecimal res = aNumber.abs(mcInt6);
assertEquals("MathContext Constructor with int precision failed", new BigDecimal("1.23809E+68"), res);
}Example 20
| Project: android-sdk-sources-for-api-level-23-master File: MathContextTest.java View source code |
/**
* java.math.MathContext#MathContext(...)
*/
public void test_MathContextConstruction() {
String a = "-12380945E+61";
BigDecimal aNumber = new BigDecimal(a);
MathContext mcIntRm6hd = new MathContext(6, RoundingMode.HALF_DOWN);
MathContext mcStr6hd = new MathContext("precision=6 roundingMode=HALF_DOWN");
MathContext mcInt6 = new MathContext(6);
MathContext mcInt134 = new MathContext(134);
// getPrecision()
assertEquals("MathContext.getPrecision() returns incorrect value", 6, mcIntRm6hd.getPrecision());
assertEquals("MathContext.getPrecision() returns incorrect value", 134, mcInt134.getPrecision());
// getRoundingMode()
assertEquals("MathContext.getRoundingMode() returns incorrect value", RoundingMode.HALF_UP, mcInt6.getRoundingMode());
assertEquals("MathContext.getRoundingMode() returns incorrect value", RoundingMode.HALF_DOWN, mcIntRm6hd.getRoundingMode());
// toString()
assertEquals("MathContext.toString() returning incorrect value", "precision=6 roundingMode=HALF_DOWN", mcIntRm6hd.toString());
assertEquals("MathContext.toString() returning incorrect value", "precision=6 roundingMode=HALF_UP", mcInt6.toString());
// equals(.)
assertEquals("Equal MathContexts are not equal ", mcIntRm6hd, mcStr6hd);
assertFalse("Different MathContexts are reported as equal ", mcInt6.equals(mcStr6hd));
assertFalse("Different MathContexts are reported as equal ", mcInt6.equals(mcInt134));
// hashCode(.)
assertEquals("Equal MathContexts have different hashcodes ", mcIntRm6hd.hashCode(), mcStr6hd.hashCode());
assertFalse("Different MathContexts have equal hashcodes ", mcInt6.hashCode() == mcStr6hd.hashCode());
assertFalse("Different MathContexts have equal hashcodes ", mcInt6.hashCode() == mcInt134.hashCode());
// other:
BigDecimal res = aNumber.abs(mcInt6);
assertEquals("MathContext Constructor with int precision failed", new BigDecimal("1.23809E+68"), res);
}Example 21
| Project: android_libcore-master File: MathContextTest.java View source code |
/**
* @tests java.math.MathContext#MathContext(...)
*/
@TestTargets({ @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "MathContext", args = { int.class }), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "MathContext", args = { int.class, java.math.RoundingMode.class }), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "MathContext", args = { java.lang.String.class }), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getPrecision", args = {}), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getRoundingMode", args = {}), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "equals", args = { java.lang.Object.class }), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "hashCode", args = {}), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "toString", args = {}) })
public void test_MathContextConstruction() {
String a = "-12380945E+61";
BigDecimal aNumber = new BigDecimal(a);
MathContext mcIntRm6hd = new MathContext(6, RoundingMode.HALF_DOWN);
MathContext mcStr6hd = new MathContext("precision=6 roundingMode=HALF_DOWN");
MathContext mcInt6 = new MathContext(6);
MathContext mcInt134 = new MathContext(134);
// getPrecision()
assertEquals("MathContext.getPrecision() returns incorrect value", 6, mcIntRm6hd.getPrecision());
assertEquals("MathContext.getPrecision() returns incorrect value", 134, mcInt134.getPrecision());
// getRoundingMode()
assertEquals("MathContext.getRoundingMode() returns incorrect value", RoundingMode.HALF_UP, mcInt6.getRoundingMode());
assertEquals("MathContext.getRoundingMode() returns incorrect value", RoundingMode.HALF_DOWN, mcIntRm6hd.getRoundingMode());
// toString()
assertEquals("MathContext.toString() returning incorrect value", "precision=6 roundingMode=HALF_DOWN", mcIntRm6hd.toString());
assertEquals("MathContext.toString() returning incorrect value", "precision=6 roundingMode=HALF_UP", mcInt6.toString());
// equals(.)
assertEquals("Equal MathContexts are not equal ", mcIntRm6hd, mcStr6hd);
assertFalse("Different MathContexts are reported as equal ", mcInt6.equals(mcStr6hd));
assertFalse("Different MathContexts are reported as equal ", mcInt6.equals(mcInt134));
// hashCode(.)
assertEquals("Equal MathContexts have different hashcodes ", mcIntRm6hd.hashCode(), mcStr6hd.hashCode());
assertFalse("Different MathContexts have equal hashcodes ", mcInt6.hashCode() == mcStr6hd.hashCode());
assertFalse("Different MathContexts have equal hashcodes ", mcInt6.hashCode() == mcInt134.hashCode());
// other:
BigDecimal res = aNumber.abs(mcInt6);
assertEquals("MathContext Constructor with int precision failed", new BigDecimal("1.23809E+68"), res);
}Example 22
| Project: android_platform_libcore-master File: MathContextTest.java View source code |
/**
* java.math.MathContext#MathContext(...)
*/
public void test_MathContextConstruction() {
String a = "-12380945E+61";
BigDecimal aNumber = new BigDecimal(a);
MathContext mcIntRm6hd = new MathContext(6, RoundingMode.HALF_DOWN);
MathContext mcStr6hd = new MathContext("precision=6 roundingMode=HALF_DOWN");
MathContext mcInt6 = new MathContext(6);
MathContext mcInt134 = new MathContext(134);
// getPrecision()
assertEquals("MathContext.getPrecision() returns incorrect value", 6, mcIntRm6hd.getPrecision());
assertEquals("MathContext.getPrecision() returns incorrect value", 134, mcInt134.getPrecision());
// getRoundingMode()
assertEquals("MathContext.getRoundingMode() returns incorrect value", RoundingMode.HALF_UP, mcInt6.getRoundingMode());
assertEquals("MathContext.getRoundingMode() returns incorrect value", RoundingMode.HALF_DOWN, mcIntRm6hd.getRoundingMode());
// toString()
assertEquals("MathContext.toString() returning incorrect value", "precision=6 roundingMode=HALF_DOWN", mcIntRm6hd.toString());
assertEquals("MathContext.toString() returning incorrect value", "precision=6 roundingMode=HALF_UP", mcInt6.toString());
// equals(.)
assertEquals("Equal MathContexts are not equal ", mcIntRm6hd, mcStr6hd);
assertFalse("Different MathContexts are reported as equal ", mcInt6.equals(mcStr6hd));
assertFalse("Different MathContexts are reported as equal ", mcInt6.equals(mcInt134));
// hashCode(.)
assertEquals("Equal MathContexts have different hashcodes ", mcIntRm6hd.hashCode(), mcStr6hd.hashCode());
assertFalse("Different MathContexts have equal hashcodes ", mcInt6.hashCode() == mcStr6hd.hashCode());
assertFalse("Different MathContexts have equal hashcodes ", mcInt6.hashCode() == mcInt134.hashCode());
// other:
BigDecimal res = aNumber.abs(mcInt6);
assertEquals("MathContext Constructor with int precision failed", new BigDecimal("1.23809E+68"), res);
}Example 23
| Project: ARTPart-master File: OldBigDecimalCompareTest.java View source code |
public void testAbsMathContextNeg() {
String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21";
BigDecimal aNumber = new BigDecimal(a);
MathContext mc = new MathContext(34, RoundingMode.UP);
assertEquals("incorrect value", "1.238096483923847545735673567457357E+53", aNumber.abs(mc).toString());
mc = new MathContext(34, RoundingMode.DOWN);
assertEquals("incorrect value", "1.238096483923847545735673567457356E+53", aNumber.abs(mc).toString());
mc = new MathContext(34, RoundingMode.FLOOR);
assertEquals("incorrect value", "1.238096483923847545735673567457356E+53", aNumber.abs(mc).toString());
mc = new MathContext(34, RoundingMode.CEILING);
assertEquals("incorrect value", "1.238096483923847545735673567457357E+53", aNumber.abs(mc).toString());
mc = new MathContext(34, RoundingMode.UNNECESSARY);
try {
aNumber.abs(mc);
fail("No ArithmeticException for RoundingMode.UNNECESSARY");
} catch (ArithmeticException expected) {
}
}Example 24
| Project: gMix-master File: NormalizedPareto.java View source code |
public static void main(String[] args) {
int runs = 1000000;
NormalizedPareto np = new NormalizedPareto(2d, 1.0d);
BigDecimal sum = new BigDecimal("0.0");
BigDecimal roundedSum = new BigDecimal("0.0");
for (int i = 0; i < runs; i++) {
double sample = np.drawSample();
sum = sum.add(new BigDecimal("" + sample));
roundedSum = roundedSum.add(new BigDecimal("" + Math.round(sample)));
}
System.out.println("avg of " + runs + " runs: " + sum.divide(new BigDecimal("" + runs), java.math.RoundingMode.HALF_UP));
System.out.println("rounded avg of " + runs + " runs: " + roundedSum.divide(new BigDecimal("" + runs), java.math.RoundingMode.HALF_UP));
}Example 25
| Project: robovm-master File: OldBigDecimalArithmeticTest.java View source code |
public void testAddMathContextNonTrivial() {
MathContext mc;
BigDecimal a, b, res;
mc = new MathContext(17, RoundingMode.FLOOR);
a = new BigDecimal("123456789012345.678");
b = new BigDecimal("100000000000000.009");
assertEquals("incorrect value", "123456789012345.67", a.round(mc).toString());
assertEquals("incorrect value", "100000000000000.00", b.round(mc).toString());
assertEquals("incorrect value", "223456789012345.67", a.round(mc).add(b.round(mc)).toString());
res = a.add(b, mc);
assertEquals("incorrect value", "223456789012345.68", res.toString());
mc = new MathContext(33, RoundingMode.UNNECESSARY);
a = new BigDecimal("1234567890123456789012345678.9012395");
b = new BigDecimal("1000000000000000090000000000.0000005");
res = a.add(b, mc);
assertEquals("Incorrect value!", "2234567890123456879012345678.90124", res.toString());
assertEquals("Incorrect scale!", 5, res.scale());
assertEquals("Incorrect precision!", 33, res.precision());
}Example 26
| Project: error-prone-master File: TemplatingTest.java View source code |
@Test
public void fullyQualifiedGlobalIdent() {
compile("class FullyQualifiedIdentExample {", " public java.math.RoundingMode example() {", " return java.math.RoundingMode.FLOOR;", " }", "}");
assertEquals(ExpressionTemplate.create(UStaticIdent.create("java.math.RoundingMode", "FLOOR", UClassType.create("java.math.RoundingMode")), UClassType.create("java.math.RoundingMode")), UTemplater.createTemplate(context, getMethodDeclaration("example")));
}Example 27
| Project: Refaster-master File: TemplatingTest.java View source code |
@Test
public void fullyQualifiedGlobalIdent() {
compile("class FullyQualifiedIdentExample {", " public java.math.RoundingMode example() {", " return java.math.RoundingMode.FLOOR;", " }", "}");
assertEquals(ExpressionTemplate.create(UStaticIdent.create("java.math.RoundingMode", "FLOOR", UClassType.create("java.math.RoundingMode")), UClassType.create("java.math.RoundingMode")), UTemplater.createTemplate(context, getMethodDeclaration("example")));
}Example 28
| Project: guava-experimental-master File: BigIntegerMath.java View source code |
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch(mode) {
case UNNECESSARY:
// fall through
checkRoundingUnnecessary(isPowerOfTwo(x));
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
/*
* Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
*
* To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 *
* logFloor + 1).
*/
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}Example 29
| Project: guava-libraries-master File: BigIntegerMath.java View source code |
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch(mode) {
case UNNECESSARY:
// fall through
checkRoundingUnnecessary(isPowerOfTwo(x));
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
/*
* Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
*
* To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 *
* logFloor + 1).
*/
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}Example 30
| Project: pig-master File: FloatRoundTo.java View source code |
/**
* java level API
* @param input expects a numeric value to round, a number of digits to keep, and an optional rounding mode.
* @return output returns a single numeric value, the number with only those digits retained
*/
@Override
public Float exec(Tuple input) throws IOException {
if (input == null || input.size() < 2)
return null;
try {
Float num = (Float) input.get(0);
Integer digits = (Integer) input.get(1);
RoundingMode mode = (input.size() >= 3) ? RoundingMode.valueOf(DataType.toInteger(input.get(2))) : RoundingMode.HALF_EVEN;
if (num == null)
return null;
BigDecimal bdnum = BigDecimal.valueOf(num);
bdnum = bdnum.setScale(digits, mode);
return bdnum.floatValue();
} catch (Exception e) {
throw new IOException("Caught exception processing input row ", e);
}
}Example 31
| Project: spork-master File: FloatRoundTo.java View source code |
/**
* java level API
* @param input expects a numeric value to round, a number of digits to keep, and an optional rounding mode.
* @return output returns a single numeric value, the number with only those digits retained
*/
@Override
public Float exec(Tuple input) throws IOException {
if (input == null || input.size() < 2)
return null;
try {
Float num = (Float) input.get(0);
Integer digits = (Integer) input.get(1);
RoundingMode mode = (input.size() >= 3) ? RoundingMode.valueOf(DataType.toInteger(input.get(2))) : RoundingMode.HALF_EVEN;
if (num == null)
return null;
BigDecimal bdnum = BigDecimal.valueOf(num);
bdnum = bdnum.setScale(digits, mode);
return bdnum.floatValue();
} catch (Exception e) {
throw new IOException("Caught exception processing input row ", e);
}
}Example 32
| Project: arquillian-showcase-master File: MortgageCalculatorBean.java View source code |
/**
* a = [ P(1 + r)^Y * r ] / [ (1 + r)^Y - 1 ]
*/
@Override
public BigDecimal calculateMonthlyPayment(double principal, double interestRate, int termYears) {
// System.out.println(getClass().getName() + ".calculateMonthlyPayment() call chain:");
// for (StackTraceElement e : Thread.currentThread().getStackTrace())
// {
// if (!e.getClassName().equals(getClass().getName()) &&
// !e.getMethodName().equals("getStackTrace") &&
// !(e.getLineNumber() < -1)) {
// System.out.println(" L " + e.getClassName() + "." + e.getMethodName() + "(line: " + e.getLineNumber() + ")");
// }
// }
BigDecimal p = new BigDecimal(principal);
int divisionScale = p.precision() + CURRENCY_DECIMALS;
BigDecimal r = new BigDecimal(interestRate).divide(ONE_HUNDRED, MathContext.UNLIMITED).divide(TWELVE, divisionScale, RoundingMode.HALF_EVEN);
BigDecimal z = r.add(BigDecimal.ONE);
BigDecimal tr = new BigDecimal(Math.pow(z.doubleValue(), termYears * 12));
return p.multiply(tr).multiply(r).divide(tr.subtract(BigDecimal.ONE), divisionScale, RoundingMode.HALF_EVEN).setScale(CURRENCY_DECIMALS, RoundingMode.HALF_EVEN);
}Example 33
| Project: bitcoin-exchange-master File: MathUtils.java View source code |
public static double roundDouble(double value, int precision, RoundingMode roundingMode) {
if (precision < 0)
throw new IllegalArgumentException();
try {
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(precision, roundingMode);
return bd.doubleValue();
} catch (Throwable t) {
log.error(t.toString());
return 0;
}
}Example 34
| Project: bitsquare-master File: MathUtils.java View source code |
public static double roundDouble(double value, int precision, RoundingMode roundingMode) {
if (precision < 0)
throw new IllegalArgumentException();
try {
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(precision, roundingMode);
return bd.doubleValue();
} catch (Throwable t) {
log.error(t.toString());
return 0;
}
}Example 35
| Project: bullsfirst-server-java-master File: EventStats.java View source code |
private void init() {
long totalNanos = lastEventNanos - firstEventNanos;
this.totalMillis = new BigDecimal(totalNanos).divide(NanosPerMilli, 0, RoundingMode.HALF_UP);
if (totalEvents == 0) {
millisPerEvent = new BigDecimal("0.000");
} else {
millisPerEvent = totalMillis.divide(new BigDecimal(totalEvents), 3, RoundingMode.HALF_UP);
}
this.initialized = true;
}Example 36
| Project: caffeine-master File: StorageTraceReader.java View source code |
@Override
public LongStream events() throws IOException {
return lines().flatMapToLong( line -> {
String[] array = line.split(",", 5);
if (array.length <= 4) {
return LongStream.empty();
}
long startBlock = Long.parseLong(array[1]);
int size = Integer.parseInt(array[2]);
int sequence = IntMath.divide(size, BLOCK_SIZE, RoundingMode.UP);
char readWrite = Character.toLowerCase(array[3].charAt(0));
return (readWrite == 'w') ? LongStream.empty() : LongStream.range(startBlock, startBlock + sequence);
});
}Example 37
| Project: DeviceConnect-Android-master File: ColorUtil.java View source code |
/**
* NOTE: Arithmetic operations in primitive types may lead to arithmetic overflow. To retain
* precision, BigDecimal objects are used.
*
* @param rgb
* @return
*/
public static int[] convertRGB_8_8_8_To_HSB_32_32_32(int[] rgb) {
int[] hsb = new int[3];
int maxChroma = Math.max(Math.max(rgb[0], rgb[1]), rgb[2]);
int minChroma = Math.min(Math.min(rgb[0], rgb[1]), rgb[2]);
int diff = maxChroma - minChroma;
// Hue
BigDecimal hue;
if (diff == 0) {
hue = BigDecimal.ZERO;
} else if (maxChroma == rgb[0]) {
float tmp = (rgb[1] - rgb[2]) / (float) diff;
if (tmp < 0) {
tmp += 6 * Math.ceil(-tmp / 6.0);
} else {
tmp -= 6 * Math.floor(tmp / 6.0);
}
hue = BigDecimal.valueOf(tmp);
} else if (maxChroma == rgb[1]) {
hue = BigDecimal.valueOf((rgb[2] - rgb[0]) / (float) diff + 2);
} else {
hue = BigDecimal.valueOf((rgb[0] - rgb[1]) / (float) diff + 4);
}
// [0, 360] -> [0, 0xffffffff]
hue = hue.multiply(BigDecimal.valueOf(0xffffffffL));
hue = hue.divide(BigDecimal.valueOf(6), RoundingMode.FLOOR);
hsb[0] = ByteBuffer.allocate(8).putLong(hue.longValue()).getInt(4);
// Saturation
if (maxChroma == 0) {
hsb[1] = 0;
} else {
// [0, 1] -> [0, 0xffffffff]
BigDecimal sat = BigDecimal.valueOf(diff);
sat = sat.multiply(BigDecimal.valueOf(0xffffffffL));
sat = sat.divide(BigDecimal.valueOf(maxChroma), RoundingMode.FLOOR);
hsb[1] = ByteBuffer.allocate(8).putLong(sat.longValue()).getInt(4);
}
// Brightness
// [0, 255] -> [0, 0xffffffff]
BigDecimal brightness = BigDecimal.valueOf(maxChroma);
brightness = brightness.multiply(BigDecimal.valueOf(0xffffffffL));
brightness = brightness.divide(BigDecimal.valueOf(0xffL), RoundingMode.FLOOR);
hsb[2] = ByteBuffer.allocate(8).putLong(brightness.longValue()).getInt(4);
return hsb;
}Example 38
| Project: DLect-master File: DownloadState.java View source code |
/**
* The number of milliseconds until completion. This is only an estimate.
*
* @return
*/
@CheckForSigned
public long estimatedCompletion() {
if (downloadTimeMillis <= 0 || currentBytes <= 0) {
return -1;
}
double speed = ((double) currentBytes) / downloadTimeMillis;
long remaining = totalSizeBytes - currentBytes;
if (remaining < 0) {
return -1;
}
return DoubleMath.roundToLong(remaining / speed, RoundingMode.HALF_UP);
}Example 39
| Project: estatio-master File: TurnoverRentRuleHelper.java View source code |
private BigDecimal doCalculateRent(final BigDecimal turnover) {
BigDecimal total = BigDecimal.ZERO;
BigDecimal prevCap = BigDecimal.ZERO;
BigDecimal cap = BigDecimal.ZERO;
BigDecimal percentage;
for (int i = 0; i < rules.length; i = i + 2) {
BigDecimal base = BigDecimal.ZERO;
if (i == rules.length - 1) {
// the last or single item
percentage = new BigDecimal(rules[i]).divide(InvoiceConstants.PERCENTAGE_DIVISOR);
if (turnover.compareTo(prevCap) > 0) {
base = turnover.subtract(prevCap);
}
} else {
percentage = new BigDecimal(rules[i + 1]).divide(InvoiceConstants.PERCENTAGE_DIVISOR);
cap = new BigDecimal(rules[i]);
if (turnover.compareTo(cap) > 0) {
base = cap.subtract(prevCap);
} else {
if (turnover.compareTo(prevCap) > 0) {
base = turnover.subtract(prevCap);
}
}
}
total = total.add(base.multiply(percentage).setScale(2, RoundingMode.HALF_UP));
prevCap = cap;
}
return total;
}Example 40
| Project: Fingra.ph_Statistics-Web-master File: NumberFormatUtil.java View source code |
public static String shortScaleConvertWithBigDecimal(BigDecimal num) {
String formatted = NumberFormat.getNumberInstance().format(num.setScale(1, RoundingMode.HALF_UP).doubleValue());
String[] vals = formatted.split(",");
int idx = vals.length;
if (idx == 1)
return formatted;
return vals[0] + ((vals[1].charAt(0) == '0') ? symbols.charAt(idx - 1) : ("." + (vals[1].charAt(0)) + symbols.charAt(idx - 1)));
}Example 41
| Project: gitools-master File: DecoratorPanelFormatters.java View source code |
static JFormattedTextField.AbstractFormatterFactory getTenDecimalsFormatter() {
return new JFormattedTextField.AbstractFormatterFactory() {
@Override
public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
NumberFormat format = DecimalFormat.getInstance();
format.setMaximumFractionDigits(10);
format.setRoundingMode(RoundingMode.HALF_UP);
InternationalFormatter formatter = new InternationalFormatter(format);
return formatter;
}
};
}Example 42
| Project: google-web-toolkit-svnmirror-master File: RoundingModeTest.java View source code |
/**
* Check the order of the enum values. This is important for serialization
* with a real JRE implementation.
*/
public void testValues() {
RoundingMode[] values = RoundingMode.values();
assertEquals(8, values.length);
int i = 0;
assertEquals(RoundingMode.UP, values[i++]);
assertEquals(RoundingMode.DOWN, values[i++]);
assertEquals(RoundingMode.CEILING, values[i++]);
assertEquals(RoundingMode.FLOOR, values[i++]);
assertEquals(RoundingMode.HALF_UP, values[i++]);
assertEquals(RoundingMode.HALF_DOWN, values[i++]);
assertEquals(RoundingMode.HALF_EVEN, values[i++]);
assertEquals(RoundingMode.UNNECESSARY, values[i++]);
}Example 43
| Project: grib2geotiff-master File: TargetPathGenerator.java View source code |
private static StringBuffer generateTargetFileName(RecordMetadata metadata, SimpleDateFormat sdf) {
StringBuffer targetFilename = new StringBuffer(metadata.getName());
if (metadata.getLevelType1() != null) {
BigDecimal bd = new BigDecimal(metadata.getLevelValue1()).stripTrailingZeros().setScale(0, RoundingMode.HALF_UP);
targetFilename.append("_").append(bd.longValue());
}
if (metadata.getLevelType2() != null) {
BigDecimal bd = new BigDecimal(metadata.getLevelValue2()).stripTrailingZeros().setScale(0, RoundingMode.HALF_UP);
targetFilename.append("_").append(bd.longValue());
}
targetFilename.append("_").append(sdf.format(metadata.getForecastTime()));
return targetFilename;
}Example 44
| Project: gwt-master File: RoundingModeTest.java View source code |
/**
* Check the order of the enum values. This is important for serialization
* with a real JRE implementation.
*/
public void testValues() {
RoundingMode[] values = RoundingMode.values();
assertEquals(8, values.length);
int i = 0;
assertEquals(RoundingMode.UP, values[i++]);
assertEquals(RoundingMode.DOWN, values[i++]);
assertEquals(RoundingMode.CEILING, values[i++]);
assertEquals(RoundingMode.FLOOR, values[i++]);
assertEquals(RoundingMode.HALF_UP, values[i++]);
assertEquals(RoundingMode.HALF_DOWN, values[i++]);
assertEquals(RoundingMode.HALF_EVEN, values[i++]);
assertEquals(RoundingMode.UNNECESSARY, values[i++]);
}Example 45
| Project: gwt-sandbox-master File: RoundingModeTest.java View source code |
/**
* Check the order of the enum values. This is important for serialization
* with a real JRE implementation.
*/
public void testValues() {
RoundingMode[] values = RoundingMode.values();
assertEquals(8, values.length);
int i = 0;
assertEquals(RoundingMode.UP, values[i++]);
assertEquals(RoundingMode.DOWN, values[i++]);
assertEquals(RoundingMode.CEILING, values[i++]);
assertEquals(RoundingMode.FLOOR, values[i++]);
assertEquals(RoundingMode.HALF_UP, values[i++]);
assertEquals(RoundingMode.HALF_DOWN, values[i++]);
assertEquals(RoundingMode.HALF_EVEN, values[i++]);
assertEquals(RoundingMode.UNNECESSARY, values[i++]);
}Example 46
| Project: gwt.svn-master File: RoundingModeTest.java View source code |
/**
* Check the order of the enum values. This is important for serialization
* with a real JRE implementation.
*/
public void testValues() {
RoundingMode[] values = RoundingMode.values();
assertEquals(8, values.length);
int i = 0;
assertEquals(RoundingMode.UP, values[i++]);
assertEquals(RoundingMode.DOWN, values[i++]);
assertEquals(RoundingMode.CEILING, values[i++]);
assertEquals(RoundingMode.FLOOR, values[i++]);
assertEquals(RoundingMode.HALF_UP, values[i++]);
assertEquals(RoundingMode.HALF_DOWN, values[i++]);
assertEquals(RoundingMode.HALF_EVEN, values[i++]);
assertEquals(RoundingMode.UNNECESSARY, values[i++]);
}Example 47
| Project: head-master File: SimpleInterestCalculationStrategyTest.java View source code |
@BeforeClass
public static void setCurrency() {
oldCurrency = Money.getDefaultCurrency();
Money.setDefaultCurrency(TestUtils.RUPEE);
oldRoundingMode = (String) MifosConfigurationManager.getInstance().getProperty(AccountingRulesConstants.CURRENCY_ROUNDING_MODE);
MifosConfigurationManager.getInstance().setProperty(AccountingRulesConstants.CURRENCY_ROUNDING_MODE, RoundingMode.HALF_UP.toString());
}Example 48
| Project: hive-0.7.0-master File: UDFRound.java View source code |
public DoubleWritable evaluate(DoubleWritable n, IntWritable i) {
if ((n == null) || (i == null)) {
return null;
}
double d = n.get();
if (Double.isNaN(d) || Double.isInfinite(d)) {
doubleWritable.set(d);
} else {
doubleWritable.set(BigDecimal.valueOf(d).setScale(i.get(), RoundingMode.HALF_UP).doubleValue());
}
return doubleWritable;
}Example 49
| Project: jadira-master File: TestPersistentMoneyMajorAmountAndCurrencyAsInteger.java View source code |
@Test
public void testPersist() {
for (int i = 0; i < moneys.length; i++) {
MoneyMajorAmountAndCurrencyAsIntegerHolder item = new MoneyMajorAmountAndCurrencyAsIntegerHolder();
item.setId(i);
item.setName("test_" + i);
item.setMoney(moneys[i]);
persist(item);
}
for (int i = 0; i < moneys.length; i++) {
MoneyMajorAmountAndCurrencyAsIntegerHolder item = find((long) i);
assertNotNull(item);
assertEquals(i, item.getId());
assertEquals("test_" + i, item.getName());
if (moneys[i] == null) {
assertNull(item.getMoney());
} else {
assertEquals(moneys[i].rounded(0, RoundingMode.DOWN).toString(), item.getMoney().toString());
}
}
verifyDatabaseTable();
}Example 50
| Project: jagger-master File: TpsTest.java View source code |
public static void main(String[] args) {
DefaultWorkloadSuggestionMaker workloadSuggestionMaker = new DefaultWorkloadSuggestionMaker(10);
BigDecimal desired = new BigDecimal(1000000000);
int maxThreads = 100;
NodeTpsRecorder stats = new NodeTpsRecorder(5);
// TpsGenerator tpsGenerator = new PowTpsGenerator(3);
TpsGenerator tpsGenerator = new RandomFactor(new PowTpsGenerator(2));
StubCreator stubCreator = new StubCreator(100L, tpsGenerator);
stats.recordStatus(0, 0, 0, 0);
for (int i = 0; i < 2000; i++) {
WorkloadConfiguration suggest = workloadSuggestionMaker.suggest(desired, stats, maxThreads);
Pair<Long, Long> generate = stubCreator.create(suggest);
stats.recordStatus(suggest.getThreads(), suggest.getDelay(), generate.getFirst(), generate.getSecond());
}
Map<Long, Pair<WorkloadConfiguration, BigDecimal>> tpsHistory = stats.getTpsHistory();
BigDecimal total = BigDecimal.ZERO;
int count = 0;
for (Pair<WorkloadConfiguration, BigDecimal> pair : tpsHistory.values()) {
count++;
BigDecimal second = pair.getSecond();
total = total.add(second);
}
BigDecimal avg = total.divide(new BigDecimal(count), 3, RoundingMode.HALF_UP);
System.out.println("avg " + avg);
}Example 51
| Project: java-presentation-manager-master File: EditDecimalConverter.java View source code |
@Override
public String visualize(PMContext ctx) throws ConverterException {
BigDecimal p = (BigDecimal) ctx.getFieldValue();
if (p == null) {
p = (BigDecimal) getValue(ctx.getEntityInstance(), ctx.getField());
}
final Integer decimals = Integer.parseInt(getConfig("decimals", "2"));
final String separator = getConfig("separator", ".");
final String value = (p == null) ? "" : p.setScale(decimals, RoundingMode.HALF_EVEN).toString().replace(".", separator);
ctx.setFieldValue(value);
return super.visualize("decimal-edit.jsp?" + "&isNull=" + (p == null) + "&withNull=" + getConfig("with-null", "false") + "&separator=" + separator + "&decimals=" + decimals);
}Example 52
| Project: javamoney-examples-master File: AmountsUseExtensionPoints.java View source code |
public static void main(String... args) {
MonetaryAmount amt = Money.of(1234.56234, "CHF");
ConsoleUtils.printDetails("Base", amt);
ConsoleUtils.printDetails("10.5 %", amt.with(MonetaryOperators.percent(10.5)));
ConsoleUtils.printDetails("10.5 o/oo", amt.with(MonetaryOperators.permil(10.5)));
ConsoleUtils.printDetails("Major Part", amt.with(MonetaryOperators.majorPart()));
ConsoleUtils.printDetails("Minor Part", amt.with(MonetaryOperators.minorPart()));
ConsoleUtils.printDetails("1/Base (Reciprocal)", amt.with(MonetaryOperators.reciprocal()));
System.out.println("Minor Part as long -> " + amt.query(MonetaryQueries.extractMinorPart()));
System.out.println("Major Part as long -> " + amt.query(MonetaryQueries.extractMajorPart()));
ConsoleUtils.printDetails("Rounded (default)", amt.with(Monetary.getDefaultRounding()));
ConsoleUtils.printDetails("Rounded (DOWN, 1 fraction digit)", amt.with(Monetary.getRounding(RoundingQueryBuilder.of().set(RoundingMode.DOWN).setScale(1).build())));
}Example 53
| Project: jinjava-master File: RoundFilter.java View source code |
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
BigDecimal result = BigDecimal.ZERO;
try {
result = new BigDecimal(Objects.toString(var));
} catch (NumberFormatException e) {
}
int precision = 0;
if (args.length > 0) {
precision = NumberUtils.toInt(args[0]);
}
String method = "common";
if (args.length > 1) {
method = args[1];
}
RoundingMode roundingMode;
switch(method) {
case "ceil":
roundingMode = RoundingMode.CEILING;
break;
case "floor":
roundingMode = RoundingMode.FLOOR;
break;
case "common":
default:
roundingMode = RoundingMode.HALF_UP;
}
return result.setScale(precision, roundingMode);
}Example 54
| Project: jspxcms304-master File: Files.java View source code |
public static String getSize(Long length) {
if (length == null) {
return "0 KB";
}
long lengthKB = length / 1024;
if (lengthKB < 1024) {
if (length % 1024 > 0) {
lengthKB++;
}
if (lengthKB == 1024) {
return "1 MB";
} else {
return lengthKB + " KB";
}
}
DecimalFormat format = new DecimalFormat("0.##");
BigDecimal lengthMB = new BigDecimal(length).divide(new BigDecimal(1024 * 1024), 2, RoundingMode.HALF_DOWN);
if (lengthMB.compareTo(new BigDecimal(1024)) < 0) {
return format.format(lengthMB) + " MB";
}
BigDecimal lengthGB = lengthMB.divide(new BigDecimal(1024), 2, RoundingMode.HALF_DOWN);
return format.format(lengthGB) + " GB";
}Example 55
| Project: jsr354-ri-master File: MonetaryTest.java View source code |
@Test
public void shouldCreateMonetaryFactory() {
MonetaryAmount monetaryAmount = Monetary.getAmountFactory(MonetaryAmountFactoryQueryBuilder.of().set(RoundingMode.DOWN).setPrecision(256).build()).setCurrency("CHF").setNumber(1234.5678).create();
assertEquals(256, monetaryAmount.getContext().getPrecision());
assertEquals(RoundingMode.DOWN, monetaryAmount.getContext().get(RoundingMode.class));
}Example 56
| Project: konik-master File: MonetarySummations.java View source code |
public static MonetarySummation precise(final MonetarySummation monetarySummation, int precision, RoundingMode roundingMode) {
MonetarySummation copy = newMonetarySummation(monetarySummation);
copy.setChargeTotal(Amounts.setPrecision(copy.getChargeTotal(), precision, roundingMode));
copy.setDuePayable(Amounts.setPrecision(copy.getDuePayable(), precision, roundingMode));
copy.setLineTotal(Amounts.setPrecision(copy.getLineTotal(), precision, roundingMode));
copy.setTotalPrepaid(Amounts.setPrecision(copy.getTotalPrepaid(), precision, roundingMode));
copy.setGrandTotal(Amounts.setPrecision(copy.getGrandTotal(), precision, roundingMode));
copy.setAllowanceTotal(Amounts.setPrecision(copy.getAllowanceTotal(), precision, roundingMode));
copy.setTaxBasisTotal(Amounts.setPrecision(copy.getTaxBasisTotal(), precision, roundingMode));
copy.setTaxTotal(Amounts.setPrecision(copy.getTaxTotal(), precision, roundingMode));
return copy;
}Example 57
| Project: mifos-head-master File: VariableInstallmentLoanScheduleRounder.java View source code |
@Override
public List<LoanScheduleEntity> round(GraceType graceType, Short gracePeriodDuration, Money loanAmount, InterestType interestType, List<LoanScheduleEntity> unroundedLoanSchedules, List<LoanScheduleEntity> allExistingLoanSchedules) {
// for variable installments - want to round all installments total amount values except for the last installment.
Money totalDue = new Money(loanAmount.getCurrency(), Double.valueOf("0"));
for (LoanScheduleEntity loanScheduleEntity : unroundedLoanSchedules) {
totalDue = totalDue.add(loanScheduleEntity.getPrincipalDue()).add(loanScheduleEntity.getInterestDue()).add(loanScheduleEntity.getTotalFeesDue());
}
BigDecimal installmentAmount = totalDue.getAmount().divide(BigDecimal.valueOf(Integer.valueOf(unroundedLoanSchedules.size())), RoundingMode.HALF_UP);
long roundedValue = Math.round(installmentAmount.doubleValue());
Money totalInstallmentMonetaryAmount = new Money(loanAmount.getCurrency(), BigDecimal.valueOf(roundedValue));
Money totalPrincipalToDate = new Money(loanAmount.getCurrency(), BigDecimal.ZERO);
int index = 0;
for (LoanScheduleEntity loanScheduleEntity : unroundedLoanSchedules) {
if (index == unroundedLoanSchedules.size() - 1) {
// last installment
loanScheduleEntity.setPrincipal(loanAmount.subtract(totalPrincipalToDate));
} else {
Money principal = totalInstallmentMonetaryAmount.subtract(loanScheduleEntity.getInterest());
loanScheduleEntity.setPrincipal(principal);
totalPrincipalToDate = totalPrincipalToDate.add(principal);
}
index++;
}
return unroundedLoanSchedules;
}Example 58
| Project: mybatis-master File: RoundingHandlersTest.java View source code |
@Test
public void shouldGetAUser() {
SqlSession session = sqlSessionFactory.openSession();
try {
Mapper mapper = session.getMapper(Mapper.class);
User user = mapper.getUser(1);
Assert.assertEquals("User1", user.getName());
Assert.assertEquals(RoundingMode.UP, user.getRoundingMode());
user = mapper.getUser2(1);
Assert.assertEquals("User1", user.getName());
Assert.assertEquals(RoundingMode.UP, user.getRoundingMode());
} finally {
session.close();
}
}Example 59
| Project: myria-master File: IntDivideExpression.java View source code |
@Override
public String getJavaString(final ExpressionOperatorParameter parameters) {
Type defaultType = checkAndReturnDefaultNumericType(parameters);
if (validTypes.contains(defaultType)) {
/* Default type is an Int or Long, so just use Java's default division. */
return getInfixBinaryString("/", parameters);
}
/* Default type if a Float or Double, so cast in a checked-way to a long. */
return new StringBuilder("com.google.common.math.DoubleMath.roundToLong(").append(getInfixBinaryString("/", parameters)).append(", java.math.RoundingMode.DOWN)").toString();
}Example 60
| Project: nebula.widgets.nattable-master File: QuotientFunction.java View source code |
@Override
public BigDecimal getValue() {
if (this.values.isEmpty()) {
return new BigDecimal(0);
}
BigDecimal result = null;
for (FunctionValue value : this.values) {
if (result == null) {
result = convertValue(value.getValue());
} else {
try {
BigDecimal divisor = convertValue(value.getValue());
if (BigDecimal.ZERO.equals(divisor)) {
//$NON-NLS-1$ //$NON-NLS-2$
throw new FunctionException("#DIV/0!", Messages.getString("FormulaParser.error.divisionByZero"));
}
result = result.divide(divisor);
} catch (ArithmeticException e) {
if (e.getMessage().startsWith("Non-terminating")) {
result = result.divide(convertValue(value.getValue()), 9, RoundingMode.HALF_UP);
} else
throw e;
}
}
}
return result;
}Example 61
| Project: olca-modules-master File: ImpactSheet.java View source code |
private void data() {
int row = 2;
int resultStartCol = ResultExport.IMPACT_HEADER.length + 1;
for (ImpactCategoryDescriptor impact : impacts) {
double value = result.getTotalImpactResult(impact).value;
writer.impactRow(sheet, row, 1, impact);
writer.cell(sheet, row, resultStartCol, value);
if (dqResult == null) {
row++;
continue;
}
RoundingMode rounding = dqResult.setup.roundingMode;
int scores = dqResult.setup.exchangeDqSystem.getScoreCount();
double[] quality = dqResult.get(impact);
writer.dataQuality(sheet, row++, resultStartCol + 1, quality, rounding, scores);
}
}Example 62
| Project: owsi-core-parent-master File: PercentageTests.java View source code |
@Test
public void percentageTest() {
PercentageBigDecimalConverter bigDecimalConverterWithPS8 = new PercentageBigDecimalConverter(8, RoundingMode.HALF_UP, 10, true, true);
PercentageBigDecimalConverter bigDecimalConverterWithPS2 = new PercentageBigDecimalConverter(2, RoundingMode.HALF_UP, 5, true, true);
PercentageBigDecimalConverter bigDecimalConverterWithoutPS8 = new PercentageBigDecimalConverter(8, RoundingMode.HALF_UP, 10, true, false);
PercentageBigDecimalConverter bigDecimalConverterWithoutPS2 = new PercentageBigDecimalConverter(2, RoundingMode.HALF_UP, 5, true, false);
{
BigDecimal bg = bigDecimalConverterWithPS2.convertToObject("51,256%", null);
Assert.assertEquals(new BigDecimal("0.51"), bg);
String s = bigDecimalConverterWithPS2.convertToString(new BigDecimal("0.51256"), null);
Assert.assertEquals("51%", s);
Assert.assertEquals("51%", CoreRenderers.percent("#0%", RoundingMode.HALF_UP).render(new BigDecimal("0.51256"), Locale.FRENCH));
}
{
BigDecimal bg = bigDecimalConverterWithPS8.convertToObject("51,256%", null);
Assert.assertEquals(new BigDecimal("0.51256000"), bg);
String s = bigDecimalConverterWithPS8.convertToString(new BigDecimal("0.51256"), null);
Assert.assertEquals("51,256%", s);
Assert.assertEquals("51,256%", CoreRenderers.percent("#0.######%", RoundingMode.HALF_UP).render(new BigDecimal("0.51256"), Locale.FRENCH));
}
{
BigDecimal bg = bigDecimalConverterWithoutPS2.convertToObject("51,256", null);
Assert.assertEquals(new BigDecimal("0.51"), bg);
String s = bigDecimalConverterWithoutPS2.convertToString(new BigDecimal("0.51256"), null);
Assert.assertEquals("51", s);
Assert.assertEquals("51", CoreRenderers.percent("#0", RoundingMode.HALF_UP).render(new BigDecimal("0.51256"), Locale.FRENCH));
}
{
BigDecimal bg = bigDecimalConverterWithoutPS8.convertToObject("51,256", null);
Assert.assertEquals(new BigDecimal("0.51256000"), bg);
String s = bigDecimalConverterWithoutPS8.convertToString(new BigDecimal("0.51256"), null);
Assert.assertEquals("51,256", s);
Assert.assertEquals("51,256", CoreRenderers.percent("#0.######", RoundingMode.HALF_UP).render(new BigDecimal("0.51256"), Locale.FRENCH));
}
}Example 63
| Project: PolyWorld-master File: PoissonDiscTest.java View source code |
@Test
public void testMinDistance() {
float graphDensity = 100f;
Rect2f area = Rect2f.createFromMinAndSize(0, 0, 512, 256);
int numSites = DoubleMath.roundToInt(area.area() * graphDensity / 1000, RoundingMode.HALF_UP);
PoissonDiscSampling sampling = new PoissonDiscSampling();
float rad = sampling.getMinRadius(area, numSites);
List<Vector2f> sample = sampling.create(area, numSites);
for (int i = 0; i < sample.size(); i++) {
Vector2f p0 = sample.get(i);
for (int j = 0; j < i; j++) {
Vector2f p1 = sample.get(j);
if (p0.distanceSquared(p1) < rad * rad) {
System.err.println("FAIL FOR " + p1);
System.err.println("EXISTING " + p0);
Assert.fail(String.format("Distance for %d/%d == %.2f", i, j, p0.distance(p1)));
}
}
}
}Example 64
| Project: Pr0-master File: AbsoluteStatisticsHelper.java View source code |
public static <T> void parseAbsoluteStatistics(ArrayList<T> list, String fieldName, Class<T> tClass, boolean average) {
BigDecimal decimal = new BigDecimal(0);
int count = 0;
for (T item : list) {
try {
Object o = ReflectionHelper.getObject(fieldName, item, tClass);
if (DecimalHelper.isDecimal(o.toString())) {
decimal = decimal.add(new BigDecimal(o.toString()));
count++;
}
} catch (IllegalAccessException e) {
throw new RuntimeException("This should never happen. If it happened you are a Loser...");
} catch (NoSuchFieldException e) {
Main.getLogger().log(Level.WARNING, "The field with the name '" + fieldName + "' could not be found!");
return;
}
}
if (!average) {
Main.getLogger().log(Level.INFO, "The total combined value of field '" + fieldName + "' is " + decimal.toString());
} else {
decimal = decimal.divide(new BigDecimal(count == 0 ? 1 : count), RoundingMode.CEILING);
Main.getLogger().log(Level.INFO, "The average value of field '" + fieldName + "' is " + decimal.toString());
}
}Example 65
| Project: sandbox-master File: WorldTimeEvent.java View source code |
public boolean matchesDaily(float fraction) {
Preconditions.checkArgument(fraction >= 0 && fraction <= 1, "fraction must be in [0..1]");
long fracInMs = DoubleMath.roundToLong(fraction * WorldTime.DAY_LENGTH, RoundingMode.HALF_UP);
long diff = getDayTimeInMs() - fracInMs;
return 2 * diff < WorldTime.TICK_EVENT_RATE && 2 * diff >= -WorldTime.TICK_EVENT_RATE;
}Example 66
| Project: scalagwt-gwt-master File: RoundingModeTest.java View source code |
/**
* Check the order of the enum values. This is important for serialization
* with a real JRE implementation.
*/
public void testValues() {
RoundingMode[] values = RoundingMode.values();
assertEquals(8, values.length);
int i = 0;
assertEquals(RoundingMode.UP, values[i++]);
assertEquals(RoundingMode.DOWN, values[i++]);
assertEquals(RoundingMode.CEILING, values[i++]);
assertEquals(RoundingMode.FLOOR, values[i++]);
assertEquals(RoundingMode.HALF_UP, values[i++]);
assertEquals(RoundingMode.HALF_DOWN, values[i++]);
assertEquals(RoundingMode.HALF_EVEN, values[i++]);
assertEquals(RoundingMode.UNNECESSARY, values[i++]);
}Example 67
| Project: SmartHome-master File: IntNormalizer.java View source code |
@Override
public Object doNormalize(Object value) {
try {
if (value instanceof BigDecimal) {
return ((BigDecimal) value).setScale(0, RoundingMode.UNNECESSARY);
}
if (value instanceof Byte) {
return new BigDecimal((Byte) value);
}
if (value instanceof Integer) {
return new BigDecimal((Integer) value);
}
if (value instanceof Long) {
return BigDecimal.valueOf((Long) value);
}
if (value instanceof String) {
return new BigDecimal((String) value).setScale(0, RoundingMode.UNNECESSARY);
}
if (value instanceof Float) {
return new BigDecimal(((Float) value).toString()).setScale(0, RoundingMode.UNNECESSARY);
}
if (value instanceof Double) {
return BigDecimal.valueOf((Double) value).setScale(0, RoundingMode.UNNECESSARY);
}
} catch (ArithmeticExceptionNumberFormatException | e) {
logger.trace("\"{}\" is not a valid integer number.", e, value);
return value;
}
logger.trace("Class \"{}\" cannot be converted to an integer number.", value.getClass().getName());
return value;
}Example 68
| Project: socialeyeser-master File: FixedTimeWindow.java View source code |
public String getHumanReadableWindowLength() {
if (windowLengthMillis < 60000L)
return new BigDecimal(windowLengthMillis / 1000.0).setScale(1, RoundingMode.HALF_UP).toString() + " s";
if (windowLengthMillis < 3600000L)
return new BigDecimal(windowLengthMillis / 60000.0).setScale(1, RoundingMode.HALF_UP).toString() + " m";
if (windowLengthMillis < 86400000L)
return new BigDecimal(windowLengthMillis / 3600000.0).setScale(1, RoundingMode.HALF_UP).toString() + " h";
else
return new BigDecimal(windowLengthMillis / 86400000.0).setScale(1, RoundingMode.HALF_UP).toString() + " d";
}Example 69
| Project: spreadsheet-master File: CellValueFormatter.java View source code |
public String getScientificNotationStringForNumericCell(double numericValue, String formattedValue, float cellWidthRatio, int width) {
BigDecimal ratio = new BigDecimal(cellWidthRatio);
BigDecimal columnWidth = new BigDecimal(width);
int numberOfDigits = columnWidth.divide(ratio, RoundingMode.DOWN).intValue();
if (numberOfDigits < 2) {
return "#";
} else {
int integerPartLength = formattedValue.indexOf(localeDecimalSymbols.getDecimalSeparator());
if (integerPartLength == -1) {
integerPartLength = formattedValue.length();
}
StringBuilder format = new StringBuilder("0");
if (integerPartLength == formattedValue.length() && numberOfDigits <= 4 && integerPartLength > numberOfDigits) {
return createFillString(numberOfDigits);
}
// Needs scientific if integer part doesn't fit or if it's only
// decimals and all decimal don't fit
boolean needsScientific = integerPartLength > numberOfDigits || (Math.abs(numericValue) < 1 && formattedValue.length() > numberOfDigits && numberOfDigits > 4);
int numberOfDecimals = 0;
if (needsScientific) {
// 0.#E10
numberOfDecimals = numberOfDigits - 5;
} else {
numberOfDecimals = numberOfDigits - (integerPartLength + 1);
}
if (numberOfDecimals > 0) {
format.append('.');
for (int i = 0; i < numberOfDecimals; i++) {
format.append('#');
}
}
if (needsScientific) {
format.append("E0");
}
if (format.length() > numberOfDigits) {
return createFillString(numberOfDigits);
}
return new DecimalFormat(format.toString(), localeDecimalSymbols).format(numericValue);
}
}Example 70
| Project: struts-master File: NumberTagTest.java View source code |
public void testSimpleCurrencyPLFormat() throws Exception {
// given
context.put(ActionContext.LOCALE, new Locale("pl", "PL"));
TestAction testAction = (TestAction) action;
testAction.setFloatNumber(120.0f);
NumberTag tag = new NumberTag();
tag.setPageContext(pageContext);
tag.setName("floatNumber");
tag.setType("currency");
// when
tag.doStartTag();
tag.doEndTag();
// then
NumberFormat format = NumberFormat.getCurrencyInstance((Locale) context.get(ActionContext.LOCALE));
format.setRoundingMode(RoundingMode.CEILING);
String expected = format.format(120.0f);
assertEquals(expected, writer.toString());
}Example 71
| Project: tabris-master File: UnitUtil.java View source code |
public static int emToPixel(Unit unit, int parentFontSize) {
when(!(unit instanceof Em)).throwIllegalArgument("Unsupported Unit");
when(parentFontSize <= 0).throwIllegalArgument("Parent FontSize must be > 0 but was " + parentFontSize);
return unit.getValue().multiply(BigDecimal.valueOf(parentFontSize)).setScale(0, RoundingMode.HALF_UP).intValue();
}Example 72
| Project: Terasology-master File: WorldTimeEvent.java View source code |
public boolean matchesDaily(float fraction) {
Preconditions.checkArgument(fraction >= 0 && fraction <= 1, "fraction must be in [0..1]");
long fracInMs = DoubleMath.roundToLong(fraction * WorldTime.DAY_LENGTH, RoundingMode.HALF_UP);
long diff = getDayTimeInMs() - fracInMs;
return 2 * diff < WorldTime.TICK_EVENT_RATE && 2 * diff >= -WorldTime.TICK_EVENT_RATE;
}Example 73
| Project: traccar-master File: DistanceHandler.java View source code |
public Position calculateDistance(Position position) {
double distance = 0.0;
double totalDistance = 0.0;
Position last = getLastPosition(position.getDeviceId());
if (last != null) {
totalDistance = last.getDouble(Position.KEY_TOTAL_DISTANCE);
if (!position.getAttributes().containsKey(Position.KEY_DISTANCE)) {
distance = DistanceCalculator.distance(position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude());
distance = BigDecimal.valueOf(distance).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
} else {
distance = position.getDouble(Position.KEY_DISTANCE);
}
}
if (!position.getAttributes().containsKey(Position.KEY_DISTANCE)) {
position.set(Position.KEY_DISTANCE, distance);
}
totalDistance = BigDecimal.valueOf(totalDistance + distance).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
position.set(Position.KEY_TOTAL_DISTANCE, totalDistance);
return position;
}Example 74
| Project: tsdr-master File: Median.java View source code |
@Override
public BigDecimal aggregate(List<Metrics> metrics) {
if (metrics.size() == 0) {
// BigDecimal has no equivalent notion of Double.NaN, so we use null
return null;
}
// Sort the list of metrics in ascending order
Collections.sort(metrics, new Comparator<Metrics>() {
@Override
public int compare(Metrics m1, Metrics m2) {
return m1.getMetricValue().compareTo(m2.getMetricValue());
}
});
final int middle = floorDiv(metrics.size(), 2);
if (metrics.size() % 2 == 0) {
final BigDecimal left = metrics.get(middle - 1).getMetricValue();
final BigDecimal right = metrics.get(middle).getMetricValue();
return left.add(right).divide(BigDecimal.valueOf(2), RoundingMode.HALF_EVEN);
} else {
return metrics.get(middle).getMetricValue();
}
}Example 75
| Project: Vloxlands-master File: MathHelper.java View source code |
public static String formatNumber(long size, int digits, int base) {
if (size == 0)
return "0";
final String[] levels = { "", "k", "m", "g", "t" };
for (int i = levels.length - 1; i > -1; i--) if (size >= (long) Math.pow(base, i)) {
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(digits);
df.setMinimumFractionDigits(digits);
df.setRoundingMode(RoundingMode.FLOOR);
return df.format(size / Math.pow(base, i)) + levels[i];
}
return null;
}Example 76
| Project: voxels-master File: VoxGameExporter.java View source code |
// write the file
@Override
protected boolean writeFile() throws IOException {
// write dimension information
int[] size = getSize();
fileOut.writeBytes((size[0] + 1) + " " + (size[1] + 1) + " " + (size[2] + 1) + "\r\n\r\n");
// get and prepare variables
int[] min = getMin();
int[] max = getMax();
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator(',');
DecimalFormat df = new DecimalFormat("#.###", otherSymbols);
df.setRoundingMode(RoundingMode.HALF_UP);
df.setGroupingUsed(false);
setActivity("Exporting to file...", false);
// write data (set flag, r, g, b)
for (int y = max[1]; y > min[1] - 1; y--) {
setProgress((1 - ((y - min[1]) / (float) size[1])) * 100);
for (int x = max[0]; x > min[0] - 1; x--) {
for (int z = min[2]; z <= max[2]; z++) {
Voxel voxel = data.searchVoxel(new int[] { x, y, z }, false);
if (voxel == null) {
fileOut.writeBytes("0 1 1 1 ");
} else {
Color color = voxel.getColor();
fileOut.writeBytes("1 " + df.format(color.getRed() / 255f) + " " + df.format(color.getGreen() / 255f) + " " + df.format(color.getBlue() / 255f) + " ");
}
}
}
}
// success
return true;
}Example 77
| Project: wattzap-ce-master File: TaxcSatoriSmartTest.java View source code |
@Test
public void checkSpeed() {
BigDecimal bd;
for (int s = 10; s < 60; s++) {
for (int i = 0; i < p.getResitanceLevels(); i++) {
int power = p.getPower(s, i);
double speed = p.getSpeed(power, i);
bd = new BigDecimal(speed).setScale(0, RoundingMode.HALF_UP);
Assert.assertEquals(bd.intValue(), s);
}
}
}Example 78
| Project: Weasis-master File: ImageInfoHelper.java View source code |
/**
* Calculate the ratio between the image and the given resolution
*
* @param imgInfo
* @param resolution
* @return
*/
public static Double calculateRatio(AcquireImageInfo imgInfo, Resolution resolution) {
try {
Objects.requireNonNull(imgInfo);
Objects.requireNonNull(resolution);
double expectedImageSize = resolution.getMaxSize();
ImageElement imgElt = imgInfo.getImage();
Integer width = (Integer) imgElt.getTagValue(TagW.ImageWidth);
Integer height = (Integer) imgElt.getTagValue(TagW.ImageHeight);
Double currentImageSize = (double) Math.max(width, height);
return BigDecimal.valueOf(expectedImageSize / currentImageSize).setScale(5, RoundingMode.HALF_UP).doubleValue();
} catch (NullPointerException e) {
LOGGER.warn("An error occurs when calculate ratio for : " + imgInfo + ", resolution=> " + resolution, e);
return null;
}
}Example 79
| Project: WorldViewer-master File: FieldFacetTrait.java View source code |
@Override
public FacetInfo getFacetInfo(Region region) {
FieldFacet2D facet = region.getFacet(clazz);
return new FacetInfo() {
@Override
public String getWorldText(int wx, int wy) {
double value = facet.getWorld(wx, wy);
return String.format("%.2f", value);
}
@Override
public int getRGB(int x, int z) {
double value = facet.get(x, z);
int round = DoubleMath.roundToInt(offset + scale * value, RoundingMode.HALF_UP);
int g = TeraMath.clamp(round, 0, 255);
return g | (g << 8) | (g << 16);
}
};
}Example 80
| Project: guava-master File: DoubleMathTest.java View source code |
// DoubleMath.roundToInt(double, RoundingMode) @GwtIncompatible public void testRoundIntegralDoubleToInt() { for (double d : INTEGRAL_DOUBLE_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { BigDecimal expected = new BigDecimal(d).setScale(0, mode); boolean isInBounds = expected.compareTo(MAX_INT_AS_BIG_DECIMAL) <= 0 & expected.compareTo(MIN_INT_AS_BIG_DECIMAL) >= 0; try { assertEquals(expected.intValue(), DoubleMath.roundToInt(d, mode)); assertTrue(isInBounds); } catch (ArithmeticException e) { assertFalse(isInBounds); } } } }
Example 81
| Project: axelor-business-suite-master File: AnalyticDistributionLineServiceSupplychainImpl.java View source code |
@Override
public BigDecimal computeAmount(AnalyticDistributionLine analyticDistributionLine) {
BigDecimal amount = BigDecimal.ZERO;
if (analyticDistributionLine.getPurchaseOrderLine() != null) {
amount = analyticDistributionLine.getPercentage().multiply(analyticDistributionLine.getPurchaseOrderLine().getExTaxTotal().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
}
if (analyticDistributionLine.getSaleOrderLine() != null) {
amount = analyticDistributionLine.getPercentage().multiply(analyticDistributionLine.getSaleOrderLine().getExTaxTotal().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
}
if (amount.compareTo(BigDecimal.ZERO) == 0) {
return super.computeAmount(analyticDistributionLine);
}
return amount;
}Example 82
| Project: behave-master File: BrowserResultColumn.java View source code |
private BigDecimal calculatePercentageDeviation(BigDecimal totalImagePixels, String output) throws IOException {
BigDecimal percentageDeviation;
try {
BigDecimal pixelDifference = new BigDecimal(output);
percentageDeviation = pixelDifference.divide(totalImagePixels, 4, RoundingMode.HALF_UP);
} catch (Exception e) {
percentageDeviation = BigDecimal.valueOf(-1);
}
return percentageDeviation.multiply(new BigDecimal(100));
}Example 83
| Project: bitfluids-master File: Tx2FluidsAdapter.java View source code |
@Override
public void onValue(Bitcoins bitcoins, Address key, Sha256Hash hash) {
FluidType type = Preconditions.checkNotNull(lookup.get(key));
try {
double price = priceService.getEurQuote();
BigDecimal eurPerBitcoin = BigDecimal.valueOf(price);
BigDecimal euros = bitcoins.multiply(eurPerBitcoin);
BigDecimal euroPrice = BigDecimal.valueOf(type.getEuroPrice());
BigDecimal anzahl = euros.divide(euroPrice, RoundingMode.HALF_UP);
BigDecimal rounded = BigDecimal.valueOf(anzahl.add(BigDecimal.valueOf(0.5)).longValue());
//is within 2% -> return rounded
// double difference = anzahl.subtract(rounded).divide(rounded, RoundingMode.HALF_UP).abs().doubleValue();
// if (difference < 0.02) {
anzahl = rounded;
// }
fluidsNotifier.onFluidPaid(new TransactionItem(type, bitcoins, anzahl.intValue(), price, hash));
} catch (RemoteSystemFail remoteSystemFail) {
fluidsNotifier.onError(remoteSystemFail.getMessage(), type, bitcoins);
}
}Example 84
| Project: BitHub-master File: CoinbaseClient.java View source code |
public void sendPayment(Author author, BigDecimal amount, String url) throws TransferFailedException {
try {
String note = "Commit payment:\n__" + author.getUsername() + "__ " + url;
Transaction transaction = new Transaction();
transaction.setTo(author.getEmail());
transaction.setAmount(Money.of(CurrencyUnit.of("BTC"), amount, RoundingMode.DOWN));
transaction.setNotes(note);
Transaction response = coinbase.sendMoney(transaction);
if (response.getStatus() != Transaction.Status.COMPLETE) {
throw new TransferFailedException();
}
} catch (CoinbaseExceptionIOException | e) {
throw new TransferFailedException(e);
}
}Example 85
| Project: camel-master File: BigDecimalPatternFormatFactory.java View source code |
@Override
public BigDecimal parse(String string) throws Exception {
if (getNumberFormat() != null) {
DecimalFormat df = (DecimalFormat) getNumberFormat();
df.setParseBigDecimal(true);
BigDecimal bd = (BigDecimal) df.parse(string.trim());
if (super.getPrecision() != -1) {
bd = bd.setScale(super.getPrecision(), RoundingMode.valueOf(super.getRounding()));
}
return bd;
} else {
return new BigDecimal(string.trim());
}
}Example 86
| Project: cloud-sample-library-master File: ChangeRatingOfBookServlet.java View source code |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String author = request.getParameter("author").trim();
String title = request.getParameter("title").trim();
int newRating = Integer.parseInt(request.getParameter("newRating").trim());
EntityManager em = PersistenceAdapter.getEntityManager();
String currentUserId = IdentityAdapter.getLoggedUserId(request);
LibraryUser userFromDatabase = (LibraryUser) em.createNamedQuery("getUserById").setParameter("userId", currentUserId).getSingleResult();
Book currentBook = (Book) em.createNamedQuery("bookByTitleAndAuthor").setParameter("bookName", title).setParameter("authorName", author).getSingleResult();
BigDecimal numberOfRatings = currentBook.getNumberOfRatings().add(new BigDecimal(1));
currentBook.setNumberOfRatings(numberOfRatings);
BigDecimal sumOfRatings = currentBook.getSumOfRatings().add(new BigDecimal(newRating));
currentBook.setSumOfRatings(sumOfRatings);
float calculatedRating = sumOfRatings.divide(numberOfRatings, 2, RoundingMode.HALF_UP).floatValue();
currentBook.setBookRating(calculatedRating);
BookLending currentLending = (BookLending) em.createNamedQuery("lendingsByUserAndBook").setParameter("user", userFromDatabase).setParameter("lendedBook", currentBook).getSingleResult();
currentLending.setRating(newRating);
em.getTransaction().begin();
em.merge(currentBook);
em.merge(currentLending);
em.getTransaction().commit();
}Example 87
| Project: data-quality-master File: FluctuateNumericString.java View source code |
@Override
protected String doGenerateMaskedField(String input) {
if (input == null || EMPTY_STRING.equals(input.trim())) {
return input;
} else {
init();
double rateToApply = rnd.nextDouble() * rate;
if (patternInteger.matcher(input).matches()) {
BigDecimal bigDecimal = new BigDecimal(input);
if (bigDecimal.abs().compareTo(new BigDecimal(Long.MAX_VALUE)) > 0) {
final BigDecimal result = bigDecimal.multiply(BigDecimal.valueOf(rateToApply + 100)).divide(new BigDecimal(100));
return result.setScale(0, RoundingMode.HALF_UP).toString();
} else {
final long result = Math.round(Long.valueOf(input) * (rateToApply + 100) / 100);
return String.valueOf(result);
}
} else {
try {
BigDecimal bigDecimal = BigDecimalParser.toBigDecimal(input);
final int decimalLength = getDecimalPrecision(input);
if (bigDecimal.abs().compareTo(new BigDecimal(Long.MAX_VALUE)) > 0) {
final BigDecimal result = bigDecimal.multiply(BigDecimal.valueOf(rateToApply + 100)).divide(new BigDecimal(100));
if (input.contains("e") || input.contains("E")) {
return String.valueOf(result.setScale(decimalLength, RoundingMode.HALF_UP).doubleValue());
} else {
return result.setScale(decimalLength, RoundingMode.HALF_UP).toString();
}
} else {
final Double doubleValue = bigDecimal.doubleValue() * (rateToApply + 100) / 100;
final BigDecimal result = new BigDecimal(doubleValue);
return String.valueOf(result.setScale(decimalLength, RoundingMode.HALF_UP).doubleValue());
}
} catch (NumberFormatException e) {
return ReplaceCharacterHelper.replaceCharacters(input, rnd);
}
}
}
}Example 88
| Project: enviroCar-app-master File: InterpolationMeasurementProviderTest.java View source code |
@Test
public void testInterpolateTwo() {
InterpolationMeasurementProvider imp = new InterpolationMeasurementProvider();
PropertyKeyEvent s1 = new PropertyKeyEvent(Measurement.PropertyKey.SPEED, 52, 1000);
PropertyKeyEvent s2 = new PropertyKeyEvent(Measurement.PropertyKey.SPEED, 95, 4000);
//the temporal center, should be the average
double result = imp.interpolateTwo(s1.getValue(), s2.getValue(), 2500, s1.getTimestamp(), s2.getTimestamp());
Assert.assertThat(result, CoreMatchers.is(73.5));
//more at the and of the window
result = imp.interpolateTwo(s1.getValue(), s2.getValue(), 3000, s1.getTimestamp(), s2.getTimestamp());
BigDecimal bd = new BigDecimal(result);
bd = bd.setScale(2, RoundingMode.HALF_UP);
Assert.assertThat(bd.doubleValue(), CoreMatchers.is(80.67));
}Example 89
| Project: fenixedu-academic-master File: DFAGratuityByNumberOfEnrolmentsPR.java View source code |
@Override
protected Money calculateDFAGratuityTotalAmountToPay(final Event event) {
final GratuityEvent gratuityEvent = (GratuityEvent) event;
final BigDecimal numberOfEnrolments = BigDecimal.valueOf(gratuityEvent.getEnrolmentsEctsForRegistration());
final BigDecimal ectsCredits = BigDecimal.valueOf(gratuityEvent.getStudentCurricularPlan().getCycle(CycleType.THIRD_CYCLE).getDefaultEcts(gratuityEvent.getExecutionYear()));
final Money result = getDfaTotalAmount().multiply(numberOfEnrolments.divide(ectsCredits, SCALE_FOR_INTERMEDIATE_CALCULATIONS, RoundingMode.HALF_EVEN));
return result.lessOrEqualThan(getDfaTotalAmount()) ? result : getDfaTotalAmount();
}Example 90
| Project: fenixedu-ist-teacher-service-master File: PersonFunctionShared.java View source code |
public void recalculateCredits() {
BigDecimal percentage = getPercentage();
if (percentage != null && getSharedFunction().getCredits() != null) {
setCredits(getSharedFunction().getCredits().multiply(percentage.divide(MAX_PERCENTAGE)).setScale(2, RoundingMode.HALF_UP).doubleValue());
} else {
setCredits(0.0);
}
}Example 91
| Project: gcexplorer-master File: CellNumberFormatter.java View source code |
@Override
public String toString(Number num) {
BigDecimal tmp = new BigDecimal(num.doubleValue());
tmp.setScale(3, RoundingMode.HALF_UP);
if (app.getUnits().equals(Units.B)) {
fmt.setMaximumFractionDigits(0);
fmt.setMinimumFractionDigits(0);
return fmt.format(tmp.doubleValue());
} else {
fmt.setMaximumFractionDigits(3);
fmt.setMinimumFractionDigits(3);
return fmt.format(tmp.doubleValue());
}
}Example 92
| Project: glowroot-master File: Formatting.java View source code |
// this mimics the javascript function of same name in gauge-values.js
@VisibleForTesting
static String displaySixDigitsOfPrecision(double value, Locale locale) {
NumberFormat format = NumberFormat.getInstance(locale);
format.setMaximumFractionDigits(20);
if (value < 1000000) {
return format.format(BigDecimal.valueOf(value).round(new MathContext(6, RoundingMode.HALF_UP)));
} else {
return format.format(Math.round(value));
}
}Example 93
| Project: gobblin-master File: LongWatermark.java View source code |
@Override
public short calculatePercentCompletion(Watermark lowWatermark, Watermark highWatermark) {
Preconditions.checkArgument(lowWatermark instanceof LongWatermark);
Preconditions.checkArgument(highWatermark instanceof LongWatermark);
long total = ((LongWatermark) highWatermark).value - ((LongWatermark) lowWatermark).value;
long pulled = this.value - ((LongWatermark) lowWatermark).value;
Preconditions.checkState(total >= 0);
Preconditions.checkState(pulled >= 0);
if (total == 0) {
return 0;
}
long percent = Math.min(100, LongMath.divide(pulled * 100, total, RoundingMode.HALF_UP));
return (short) percent;
}Example 94
| Project: hive_blinkdb-master File: UDFRound.java View source code |
public DoubleWritable evaluate(DoubleWritable n, IntWritable i) {
if ((n == null) || (i == null)) {
return null;
}
double d = n.get();
if (Double.isNaN(d) || Double.isInfinite(d)) {
doubleWritable.set(d);
} else {
doubleWritable.set(BigDecimal.valueOf(d).setScale(i.get(), RoundingMode.HALF_UP).doubleValue());
}
return doubleWritable;
}Example 95
| Project: Hive_optimization-master File: UDFRound.java View source code |
public DoubleWritable evaluate(DoubleWritable n, IntWritable i) {
if ((n == null) || (i == null)) {
return null;
}
double d = n.get();
if (Double.isNaN(d) || Double.isInfinite(d)) {
doubleWritable.set(d);
} else {
doubleWritable.set(BigDecimal.valueOf(d).setScale(i.get(), RoundingMode.HALF_UP).doubleValue());
}
return doubleWritable;
}Example 96
| Project: howl-master File: UDFRound.java View source code |
public DoubleWritable evaluate(DoubleWritable n, IntWritable i) {
if ((n == null) || (i == null)) {
return null;
}
double d = n.get();
if (Double.isNaN(d) || Double.isInfinite(d)) {
doubleWritable.set(d);
} else {
doubleWritable.set(BigDecimal.valueOf(d).setScale(i.get(), RoundingMode.HALF_UP).doubleValue());
}
return doubleWritable;
}Example 97
| Project: Hydrograph-master File: WritableConverter.java View source code |
@Override
public Object getValue(Writable writable) {
// HiveDecimal object does not have method to get BigDecimal value.
// So creating the BigDecimal object from double and setting the
// same scale which HiveDecimal object has.
HiveDecimal hiveDecimal = ((HiveDecimalWritable) writable).getHiveDecimal();
return new BigDecimal(hiveDecimal.doubleValue()).setScale(hiveDecimal.scale(), RoundingMode.HALF_UP);
}Example 98
| Project: jbasics-master File: MathContextValueTypeFactoryTest.java View source code |
@Test
public void testCreate() {
MathContext mc = MathContextValueTypeFactory.SHARED_INSTANCE.create("32, half_even");
Assert.assertEquals(new MathContext(32, RoundingMode.HALF_EVEN), mc);
mc = MathContextValueTypeFactory.SHARED_INSTANCE.create("32");
Assert.assertEquals(new MathContext(32), mc);
mc = MathContextValueTypeFactory.SHARED_INSTANCE.create("32, floor");
Assert.assertEquals(new MathContext(32, RoundingMode.FLOOR), mc);
mc = MathContextValueTypeFactory.SHARED_INSTANCE.create(null);
Assert.assertSame(MathContextValueTypeFactory.DEFAULT_MATH_CONTEXT, mc);
mc = MathContextValueTypeFactory.SHARED_INSTANCE.create("981a, blub");
Assert.assertSame(MathContextValueTypeFactory.DEFAULT_MATH_CONTEXT, mc);
mc = MathContextValueTypeFactory.SHARED_INSTANCE.create("48, blub");
Assert.assertEquals(new MathContext(48), mc);
mc = MathContextValueTypeFactory.SHARED_INSTANCE.create("DECIMAL256");
Assert.assertEquals(MathContextValueTypeFactory.StandardTypes.DECIMAL256.ctx, mc);
}Example 99
| Project: jdk7u-jdk-master File: IsEnum.java View source code |
public static void main(String argv[]) {
int failures = 0;
failures += test(IsEnum.class, false);
failures += test(String.class, false);
failures += test(Enum.class, false);
failures += test(java.math.RoundingMode.class, true);
// Classes in java.lang.annoation
failures += test(Annotation.class, false);
failures += test(ElementType.class, true);
failures += test(Retention.class, false);
failures += test(RetentionPolicy.class, true);
failures += test(Target.class, false);
failures += test(EnumPoseur.class, false);
// Classes for specialized enum constants aren't enum's
failures += test(SpecialEnum.class, true);
failures += test(SpecialEnum.RED.getClass(), false);
failures += test(SpecialEnum.GREEN.getClass(), true);
if (failures > 0) {
throw new RuntimeException("Unexepcted enum status detected.");
}
}Example 100
| Project: liferay-portal-master File: BigDecimalUtil.java View source code |
public static double divide(Number x, Number y, int scale, RoundingMode roundingMode) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
BigDecimal xBigDecimal = new BigDecimal(x.toString());
BigDecimal yBigDecimal = new BigDecimal(y.toString());
BigDecimal resultBigDecimal = xBigDecimal.divide(yBigDecimal, scale, roundingMode);
return resultBigDecimal.doubleValue();
}Example 101
| Project: lucene-solr-master File: CeilingEvaluator.java View source code |
@Override
public Number evaluate(Tuple tuple) throws IOException {
List<BigDecimal> results = evaluateAll(tuple);
// one found in the constructor could become != 1
if (1 != results.size()) {
throw new IOException(String.format(Locale.ROOT, "%s(...) only works with a 1 value but %d were provided", constructingFactory.getFunctionName(getClass()), results.size()));
}
if (null == results.get(0)) {
return null;
}
return normalizeType(results.get(0).setScale(0, RoundingMode.CEILING));
}