List of usage examples for java.math BigDecimal unscaledValue
public BigInteger unscaledValue()
From source file:Main.java
public static void main(String[] args) { BigDecimal bg1 = new BigDecimal("123.12"); BigDecimal bg2 = new BigDecimal("-245.67"); // assign unscaledValue of bg1,bg2 to bi1,bi2 BigInteger bi1 = bg1.unscaledValue(); BigInteger bi2 = bg2.unscaledValue(); String str1 = "The Unscaled Value of " + bg1 + " is " + bi1; String str2 = "The Unscaled Value of " + bg2 + " is " + bi2; System.out.println(str1);//from w w w . j a v a 2 s. co m System.out.println(str2); }
From source file:org.jpox.util.SQLFormat.java
/** * Formats the given BigDecimal value into a SQL floating-point literal. * BigDecimal.toString() is not well suited to this purpose because it never * uses E-notation, which causes some values with large exponents to be * output as long strings with tons of zeroes in them. *//www . ja va 2 s . c om * @param bd The number to format. * * @return The formatted String. */ public static String format(BigDecimal bd) { String digits = bd.unscaledValue().abs().toString(); int scale = bd.scale(); int len = digits.length(); /* Normalize by removing any trailing zeroes. */ while (len > 1 && digits.charAt(len - 1) == '0') { --scale; --len; } if (len < digits.length()) { digits = digits.substring(0, len); } StringBuffer sb = new StringBuffer(); if (bd.signum() < 0) { sb.append('-'); } int exponent = len - scale; if (exponent < 0 || exponent > len) { /* Output in E-notation. */ sb.append('.').append(digits).append('E').append(exponent); } else if (exponent == len) { /* Output as an integer. */ sb.append(digits); } else { /* Output as "intDigits.fracDigits". */ sb.append(digits.substring(0, exponent)).append('.').append(digits.substring(exponent)); } return sb.toString(); }
From source file:org.apache.carbondata.core.util.DataTypeUtil.java
/** * This method will convert a big decimal value to bytes * * @param num//from w w w .j ava 2s . c o m * @return */ public static byte[] bigDecimalToByte(BigDecimal num) { BigInteger sig = new BigInteger(num.unscaledValue().toString()); int scale = num.scale(); byte[] bscale = new byte[] { (byte) (scale) }; byte[] buff = sig.toByteArray(); byte[] completeArr = new byte[buff.length + bscale.length]; System.arraycopy(bscale, 0, completeArr, 0, bscale.length); System.arraycopy(buff, 0, completeArr, bscale.length, buff.length); return completeArr; }
From source file:net.sf.jasperreports.data.cache.BigDecimalStore.java
@Override public void addValue(Object object) { if (!(object instanceof BigDecimal)) { throw new IllegalArgumentException(); }/* w ww .j a va 2s .c o m*/ BigDecimal value = (BigDecimal) object; BigInteger unscaledValue = value.unscaledValue(); int scale = value.scale(); valueStore.addValue(unscaledValue); scaleStore.addValue(scale); }
From source file:nl.strohalm.cyclos.utils.conversion.FixedLengthNumberConverter.java
public String toString(final T object) { final BigDecimal number = CoercionHelper.coerce(BigDecimal.class, object); if (number == null) { return null; }/*from w w w .j a v a2 s .c om*/ return StringUtils.leftPad(number.unscaledValue().toString(), precision, '0'); }
From source file:org.dbrain.data.jackson.serializers.JsonBigDecimalSerializer.java
@Override public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException { if (value != null) { // Does it have more that 15 significant digits ? BigInteger unscaled = value.unscaledValue(); if (unscaled.compareTo(MIN_VALUE) >= 0 && unscaled.compareTo(MAX_VALUE) <= 0) { jgen.writeNumber(value);/* w w w . j a v a2 s . c o m*/ } else { jgen.writeString(value.toString()); } } else { jgen.writeNull(); } }
From source file:com.rabbitmq.client.impl.ValueWriter.java
public final void writeFieldValue(Object value) throws IOException { if (value instanceof String) { writeOctet('S'); writeLongstr((String) value); } else if (value instanceof LongString) { writeOctet('S'); writeLongstr((LongString) value); } else if (value instanceof Integer) { writeOctet('I'); writeLong((Integer) value); } else if (value instanceof BigDecimal) { writeOctet('D'); BigDecimal decimal = (BigDecimal) value; writeOctet(decimal.scale());/*from w ww .j a v a 2 s. c o m*/ BigInteger unscaled = decimal.unscaledValue(); if (unscaled.bitLength() > 32) /*Integer.SIZE in Java 1.5*/ throw new IllegalArgumentException("BigDecimal too large to be encoded"); writeLong(decimal.unscaledValue().intValue()); } else if (value instanceof Date) { writeOctet('T'); writeTimestamp((Date) value); } else if (value instanceof Map) { writeOctet('F'); // Ignore the warnings here. We hate erasure // (not even a little respect) // (We even have trouble recognising it.) @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) value; writeTable(map); } else if (value instanceof Byte) { writeOctet('b'); out.writeByte((Byte) value); } else if (value instanceof Double) { writeOctet('d'); out.writeDouble((Double) value); } else if (value instanceof Float) { writeOctet('f'); out.writeFloat((Float) value); } else if (value instanceof Long) { writeOctet('l'); out.writeLong((Long) value); } else if (value instanceof Short) { writeOctet('s'); out.writeShort((Short) value); } else if (value instanceof Boolean) { writeOctet('t'); out.writeBoolean((Boolean) value); } else if (value instanceof byte[]) { writeOctet('x'); writeLong(((byte[]) value).length); out.write((byte[]) value); } else if (value == null) { writeOctet('V'); } else if (value instanceof List) { writeOctet('A'); writeArray((List<?>) value); } else { throw new IllegalArgumentException("Invalid value type: " + value.getClass().getName()); } }
From source file:ru.orangesoftware.financisto.widget.AmountInput.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == requestId) { String amount = data.getStringExtra(EXTRA_AMOUNT); if (amount != null) { try { BigDecimal d = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP); setAmount(d.unscaledValue().longValue()); } catch (NumberFormatException ex) { }//from ww w.ja v a2 s. co m } } } }
From source file:org.apache.hadoop.hive.serde2.io.BigDecimalWritable.java
public void set(BigDecimal value) { value = value.stripTrailingZeros();//from w ww . j av a 2s.c o m if (value.compareTo(BigDecimal.ZERO) == 0) { // Special case for 0, because java doesn't strip zeros correctly on that number. value = BigDecimal.ZERO; } set(value.unscaledValue().toByteArray(), value.scale()); }
From source file:org.apache.hadoop.hive.ql.optimizer.optiq.translator.RexNodeConverter.java
protected RexNode convert(ExprNodeConstantDesc literal) throws OptiqSemanticException { RexBuilder rexBuilder = cluster.getRexBuilder(); RelDataTypeFactory dtFactory = rexBuilder.getTypeFactory(); PrimitiveTypeInfo hiveType = (PrimitiveTypeInfo) literal.getTypeInfo(); RelDataType optiqDataType = TypeConverter.convert(hiveType, dtFactory); PrimitiveCategory hiveTypeCategory = hiveType.getPrimitiveCategory(); ConstantObjectInspector coi = literal.getWritableObjectInspector(); Object value = ObjectInspectorUtils.copyToStandardJavaObject(coi.getWritableConstantValue(), coi); RexNode optiqLiteral = null;/*from w w w.j a v a 2 s .com*/ // TODO: Verify if we need to use ConstantObjectInspector to unwrap data switch (hiveTypeCategory) { case BOOLEAN: optiqLiteral = rexBuilder.makeLiteral(((Boolean) value).booleanValue()); break; case BYTE: byte[] byteArray = new byte[] { (Byte) value }; ByteString bs = new ByteString(byteArray); optiqLiteral = rexBuilder.makeBinaryLiteral(bs); break; case SHORT: optiqLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Short) value), optiqDataType); break; case INT: optiqLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Integer) value)); break; case LONG: optiqLiteral = rexBuilder.makeBigintLiteral(new BigDecimal((Long) value)); break; // TODO: is Decimal an exact numeric or approximate numeric? case DECIMAL: if (value instanceof HiveDecimal) { value = ((HiveDecimal) value).bigDecimalValue(); } else if (value instanceof Decimal128) { value = ((Decimal128) value).toBigDecimal(); } if (value == null) { // We have found an invalid decimal value while enforcing precision and // scale. Ideally, // we would replace it with null here, which is what Hive does. However, // we need to plumb // this thru up somehow, because otherwise having different expression // type in AST causes // the plan generation to fail after CBO, probably due to some residual // state in SA/QB. // For now, we will not run CBO in the presence of invalid decimal // literals. throw new OptiqSemanticException( "Expression " + literal.getExprString() + " is not a valid decimal"); // TODO: return createNullLiteral(literal); } BigDecimal bd = (BigDecimal) value; BigInteger unscaled = bd.unscaledValue(); if (unscaled.compareTo(MIN_LONG_BI) >= 0 && unscaled.compareTo(MAX_LONG_BI) <= 0) { optiqLiteral = rexBuilder.makeExactLiteral(bd); } else { // CBO doesn't support unlimited precision decimals. In practice, this // will work... // An alternative would be to throw CboSemanticException and fall back // to no CBO. RelDataType relType = cluster.getTypeFactory().createSqlType(SqlTypeName.DECIMAL, bd.scale(), unscaled.toString().length()); optiqLiteral = rexBuilder.makeExactLiteral(bd, relType); } break; case FLOAT: optiqLiteral = rexBuilder.makeApproxLiteral(new BigDecimal((Float) value), optiqDataType); break; case DOUBLE: optiqLiteral = rexBuilder.makeApproxLiteral(new BigDecimal((Double) value), optiqDataType); break; case CHAR: if (value instanceof HiveChar) value = ((HiveChar) value).getValue(); optiqLiteral = rexBuilder.makeLiteral((String) value); break; case VARCHAR: if (value instanceof HiveVarchar) value = ((HiveVarchar) value).getValue(); optiqLiteral = rexBuilder.makeLiteral((String) value); break; case STRING: optiqLiteral = rexBuilder.makeLiteral((String) value); break; case DATE: Calendar cal = new GregorianCalendar(); cal.setTime((Date) value); optiqLiteral = rexBuilder.makeDateLiteral(cal); break; case TIMESTAMP: optiqLiteral = rexBuilder.makeTimestampLiteral((Calendar) value, RelDataType.PRECISION_NOT_SPECIFIED); break; case BINARY: case VOID: case UNKNOWN: default: throw new RuntimeException("UnSupported Literal"); } return optiqLiteral; }