/** * Returns a BigDecimal from a ValueLink formatted amount String * * @param amount The ValueLink formatted amount String * @return BigDecimal object */ public BigDecimal getAmount(String amount) { if (amount == null) { return BigDecimal.ZERO; } BigDecimal amountBd = new BigDecimal(amount); return amountBd.movePointLeft(2); }
public static BigDecimal movePointLeft(BigDecimal decimal) { if (decimal != null) { return decimal.movePointLeft(2); } else { return BigDecimalUtils.ZERO; } }
/** update the balance of the account as displayed at the top of the screen. */ public void updateBalance() { accountInfo.moveToFirst(); String amountNoDecimal = accountInfo.getString(accountInfo.getColumnIndex(AccountData.ACCOUNT_BALANCE)); BigDecimal accountBalance = new BigDecimal(amountNoDecimal); accountBalance = accountBalance.movePointLeft(2); mAccountBalance.setTextColor(Color.WHITE); mHeader.setBackgroundColor(AccountData.GREEN); if (accountBalance.signum() < 0) { mHeader.setBackgroundColor(AccountData.RED); } mAccountName.setText( accountInfo.getString(accountInfo.getColumnIndex(AccountData.ACCOUNT_NAME))); mAccountBalance.setText(accountBalance.toPlainString()); }
static void unmarshalIn( org.omg.CORBA.portable.InputStream s, TypeCode typeCode, long[] la, Object[] oa) { int type = typeCode.kind().value(); long l = 0; Object o = oa[0]; switch (type) { case TCKind._tk_null: case TCKind._tk_void: case TCKind._tk_native: // Nothing to read break; case TCKind._tk_short: l = s.read_short() & 0xFFFFL; break; case TCKind._tk_ushort: l = s.read_ushort() & 0xFFFFL; break; case TCKind._tk_enum: case TCKind._tk_long: l = s.read_long() & 0xFFFFFFFFL; break; case TCKind._tk_ulong: l = s.read_ulong() & 0xFFFFFFFFL; break; case TCKind._tk_float: l = Float.floatToIntBits(s.read_float()) & 0xFFFFFFFFL; break; case TCKind._tk_double: l = Double.doubleToLongBits(s.read_double()); break; case TCKind._tk_char: l = s.read_char() & 0xFFFFL; break; case TCKind._tk_octet: l = s.read_octet() & 0xFFL; break; case TCKind._tk_boolean: if (s.read_boolean()) l = 1; else l = 0; break; case TCKind._tk_any: o = s.read_any(); break; case TCKind._tk_TypeCode: o = s.read_TypeCode(); break; case TCKind._tk_Principal: o = s.read_Principal(); break; case TCKind._tk_objref: if (o instanceof Streamable) ((Streamable) o)._read(s); else o = s.read_Object(); break; case TCKind._tk_longlong: l = s.read_longlong(); break; case TCKind._tk_ulonglong: l = s.read_ulonglong(); break; case TCKind._tk_wchar: l = s.read_wchar() & 0xFFFFL; break; case TCKind._tk_string: o = s.read_string(); break; case TCKind._tk_wstring: o = s.read_wstring(); break; case TCKind._tk_value: case TCKind._tk_value_box: o = ((org.omg.CORBA_2_3.portable.InputStream) s).read_value(); break; case TCKind._tk_fixed: try { // _REVISIT_ As soon as the java-rtf adds digits and scale parameters to // InputStream, this check will be unnecessary if (s instanceof CDRInputStream) { o = ((CDRInputStream) s).read_fixed(typeCode.fixed_digits(), typeCode.fixed_scale()); } else { BigDecimal bigDecimal = s.read_fixed(); o = bigDecimal.movePointLeft((int) typeCode.fixed_scale()); } } catch (BadKind badKind) { // impossible } break; case TCKind._tk_struct: case TCKind._tk_union: case TCKind._tk_sequence: case TCKind._tk_array: case TCKind._tk_alias: case TCKind._tk_except: ((Streamable) o)._read(s); break; case TCKind._tk_abstract_interface: o = ((org.omg.CORBA_2_3.portable.InputStream) s).read_abstract_interface(); break; case TCKind._tk_longdouble: // Unspecified for Java default: ORBUtilSystemException wrapper = ORBUtilSystemException.get( (com.sun.corba.se.spi.orb.ORB) s.orb(), CORBALogDomains.RPC_PRESENTATION); throw wrapper.typecodeNotSupported(); } oa[0] = o; la[0] = l; }
@Override public void parse( CharSequence text, ParseLog status, AttributeQuery attributes, Map<ChronoElement<?>, Object> parsedResult, FormatStep step) { Leniency leniency = step.getAttribute(Attributes.LENIENCY, attributes, Leniency.SMART); int effectiveMin = 0; int effectiveMax = 9; if (!leniency.isLax() || this.fixedWidth) { effectiveMin = this.minDigits; effectiveMax = this.maxDigits; } int len = text.length(); if (status.getPosition() >= len) { if (effectiveMin > 0) { status.setError( status.getPosition(), "Expected fraction digits not found for: " + this.element.name()); } return; } if (this.hasDecimalSeparator()) { this.decimalSeparator.parse(text, status, attributes, null, step); if (status.isError()) { if (effectiveMin == 0) { status.clearError(); } return; } } int current = status.getPosition(); int minEndPos = current + effectiveMin; int maxEndPos = Math.min(current + effectiveMax, len); if (minEndPos > len) { status.setError(status.getPosition(), "Expected at least " + effectiveMin + " digits."); return; } char zeroDigit = step.getAttribute(Attributes.ZERO_DIGIT, attributes, Character.valueOf('0')).charValue(); long total = 0; while (current < maxEndPos) { int digit = text.charAt(current) - zeroDigit; if ((digit >= 0) && (digit <= 9)) { total = total * 10 + digit; current++; } else if (current < minEndPos) { status.setError(status.getPosition(), "Expected at least " + effectiveMin + " digits."); return; } else { break; } } BigDecimal fraction = new BigDecimal(total); fraction = fraction.movePointLeft(current - status.getPosition()); if (this.element.name().equals("NANO_OF_SECOND")) { Integer min = Integer.valueOf(0); Integer max = MRD_MINUS_1; Integer num = this.getRealValue(fraction, min, max); parsedResult.put(this.element, num); } else { // hier nur prototypischer Wert, später fraktionalen Wert bestimmen parsedResult.put(FractionalElement.FRACTION, fraction); parsedResult.put(this.element, this.element.getDefaultMinimum()); } status.setPosition(current); }
@Override public Object parseObject(String source, ParsePosition pos) { int ix = pos.getIndex(); int len = source.length(); int sign = 1; int mod = 0; int scale = 0; int exp = 0; boolean match = false; char c = 0; BigDecimal n = BigDecimal.ZERO; if (ix < len) { c = source.charAt(ix); if (c == '+' || c == '-') { sign = c == '-' ? -1 : 1; ix++; } } ix--; while (++ix < len) { c = source.charAt(ix); // System.out.println("c="+c+"; n="+n); if (Character.isDigit(c)) { int d = Character.digit(c, 10); n = n.multiply(BigDecimal.TEN); n = n.add(BigDecimal.valueOf(d)); scale += mod; match = true; // System.out.println("->"+d+"; n="+n); } else if (c == '.' && mod == 0) { mod = 1; } else { if (!match) { pos.setErrorIndex(ix); return null; } break; } } if (match && ix < len && (c == 'E' || c == 'e')) { match = false; if (++ix < len) { int esign = 1; c = source.charAt(ix); if (c == '+' || c == '-') { esign = c == '-' ? -1 : 1; } else ix--; while (++ix < len) { c = source.charAt(ix); if (Character.isDigit(c)) { int d = Character.digit(c, 10); exp = exp * 10 + d; match = true; } } exp *= esign; } } if (!match) { pos.setErrorIndex(ix); return null; } scale -= exp; n = n.movePointLeft(scale); if (sign < 0) n = n.negate(); pos.setIndex(ix); return n; }
private String formatDecimal(String start, SchemaType sType) { BigDecimal result = new BigDecimal(start); XmlDecimal xmlD; xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null; xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null; boolean minInclusive = true, maxInclusive = true; xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); if (xmlD != null) { BigDecimal minExcl = xmlD.getBigDecimalValue(); if (min == null || min.compareTo(minExcl) < 0) { min = minExcl; minInclusive = false; } } xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); if (xmlD != null) { BigDecimal maxExcl = xmlD.getBigDecimalValue(); if (max == null || max.compareTo(maxExcl) > 0) { max = maxExcl; maxInclusive = false; } } xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); int totalDigits = -1; if (xmlD != null) { totalDigits = xmlD.getBigDecimalValue().intValue(); StringBuffer sb = new StringBuffer(totalDigits); for (int i = 0; i < totalDigits; i++) sb.append('9'); BigDecimal digitsLimit = new BigDecimal(sb.toString()); if (max != null && max.compareTo(digitsLimit) > 0) { max = digitsLimit; maxInclusive = true; } digitsLimit = digitsLimit.negate(); if (min != null && min.compareTo(digitsLimit) < 0) { min = digitsLimit; minInclusive = true; } } int sigMin = min == null ? 1 : result.compareTo(min); int sigMax = max == null ? -1 : result.compareTo(max); boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive; boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive; // Compute the minimum increment xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS); int fractionDigits = -1; BigDecimal increment; if (xmlD == null) increment = new BigDecimal(1); else { fractionDigits = xmlD.getBigDecimalValue().intValue(); if (fractionDigits > 0) { StringBuffer sb = new StringBuffer("0."); for (int i = 1; i < fractionDigits; i++) sb.append('0'); sb.append('1'); increment = new BigDecimal(sb.toString()); } else increment = new BigDecimal(1); } if (minOk && maxOk) { // OK } else if (minOk && !maxOk) { // TOO BIG if (maxInclusive) result = max; else result = max.subtract(increment); } else if (!minOk && maxOk) { // TOO SMALL if (minInclusive) result = min; else result = min.add(increment); } else { // MIN > MAX!! } // We have the number // Adjust the scale according to the totalDigits and fractionDigits int digits = 0; BigDecimal ONE = new BigDecimal(BigInteger.ONE); for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++) n = n.movePointLeft(1); if (fractionDigits > 0) if (totalDigits >= 0) result.setScale(Math.max(fractionDigits, totalDigits - digits)); else result.setScale(fractionDigits); else if (fractionDigits == 0) result.setScale(0); return result.toString(); }
/** * This probably should be Currency responsibility. Even then, it may need to be customized for * specialty apps because there are other cases, where the smallest increment is not the smallest * unit. */ Money minimumIncrement() { BigDecimal one = new BigDecimal(1); BigDecimal increment = one.movePointLeft(currency.getDefaultFractionDigits()); return Money.valueOf(increment, currency); }
public static BigDecimal sqrt(BigDecimal squarD, int scalar) { // Static constants - perhaps initialize in class Vladimir! BigDecimal TWO = new BigDecimal(2); double SQRT_10 = 3.162277660168379332; MathContext rootMC = new MathContext(scalar); // General number and precision checking int sign = squarD.signum(); if (sign == -1) throw new ArithmeticException("\nSquare root of a negative number: " + squarD); else if (sign == 0) return squarD.round(rootMC); int prec = rootMC.getPrecision(); // the requested precision if (prec == 0) throw new IllegalArgumentException("\nMost roots won't have infinite precision = 0"); // Initial precision is that of double numbers 2^63/2 ~ 4E18 int BITS = 62; // 63-1 an even number of number bits int nInit = 16; // precision seems 16 to 18 digits MathContext nMC = new MathContext(18, RoundingMode.HALF_UP); // Iteration variables, for the square root x and the reciprocal v BigDecimal x = null, e = null; // initial x: x0 ~ sqrt() BigDecimal v = null, g = null; // initial v: v0 = 1/(2*x) // Estimate the square root with the foremost 62 bits of squarD BigInteger bi = squarD.unscaledValue(); // bi and scale are a tandem int biLen = bi.bitLength(); int shift = Math.max(0, biLen - BITS + (biLen % 2 == 0 ? 0 : 1)); // even // shift.. bi = bi.shiftRight(shift); // ..floors to 62 or 63 bit BigInteger double root = Math.sqrt(bi.doubleValue()); BigDecimal halfBack = new BigDecimal(BigInteger.ONE.shiftLeft(shift / 2)); int scale = squarD.scale(); if (scale % 2 == 1) // add half scales of the root to odds.. root *= SQRT_10; // 5 -> 2, -5 -> -3 need half a scale more.. scale = (int) Math.floor(scale / 2.); // ..where 100 -> 10 shifts the // scale // Initial x - use double root - multiply by halfBack to unshift - set // new scale x = new BigDecimal(root, nMC); x = x.multiply(halfBack, nMC); // x0 ~ sqrt() if (scale != 0) x = x.movePointLeft(scale); if (prec < nInit) // for prec 15 root x0 must surely be OK return x.round(rootMC); // return small prec roots without // iterations // Initial v - the reciprocal v = BigDecimal.ONE.divide(TWO.multiply(x), nMC); // v0 = 1/(2*x) // Collect iteration precisions beforehand ArrayList<Integer> nPrecs = new ArrayList<Integer>(); assert nInit > 3 : "Never ending loop!"; // assume nInit = 16 <= prec // Let m be the exact digits precision in an earlier! loop for (int m = prec + 1; m > nInit; m = m / 2 + (m > 100 ? 1 : 2)) nPrecs.add(m); // The loop of "Square Root by Coupled Newton Iteration" for simpletons for (int i = nPrecs.size() - 1; i > -1; i--) { // Increase precision - next iteration supplies n exact digits nMC = new MathContext( nPrecs.get(i), (i % 2 == 1) ? RoundingMode.HALF_UP : RoundingMode.HALF_DOWN); // Next x // e = d - x^2 e = squarD.subtract(x.multiply(x, nMC), nMC); if (i != 0) x = x.add(e.multiply(v, nMC)); // x += e*v ~ sqrt() else { x = x.add(e.multiply(v, rootMC), rootMC); // root x is ready! break; } // Next v // g = 1 - 2*x*v g = BigDecimal.ONE.subtract(TWO.multiply(x).multiply(v, nMC)); v = v.add(g.multiply(v, nMC)); // v += g*v ~ 1/2/sqrt() } return x; // return sqrt(squarD) with precision of rootMC }