Java Code Examples for java.math.BigDecimal#toBigIntegerExact()

The following examples show how to use java.math.BigDecimal#toBigIntegerExact() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BigIntegerScalar.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
public BigIntegerScalar() {

        super(Scalars.GraphQLBigInteger.getName(),
                new Converter() {
                    @Override
                    public Object fromBigDecimal(BigDecimal bigDecimal) {
                        return bigDecimal.toBigIntegerExact();
                    }

                    @Override
                    public Object fromBigInteger(BigInteger bigInteger) {
                        return bigInteger;
                    }

                },
                BigInteger.class, Long.class, long.class);
    }
 
Example 2
Source File: SochainAPI.java    From cashuwallet with MIT License 5 votes vote down vote up
@Override
public BigInteger getBalance(String address) {
    try {
        String url = baseUrl.replace("*", "get_address_balance") + "/" + address;
        JSONObject data = new JSONObject(urlFetch(url));
        data = data.getJSONObject("data");
        BigDecimal confirmed = new BigDecimal(data.getString("confirmed_balance"));
        BigDecimal unconfirmed = new BigDecimal(data.getString("unconfirmed_balance"));
        BigDecimal balance = confirmed.add(unconfirmed);
        balance = balance.multiply(BigDecimal.TEN.pow(8));
        return balance.toBigIntegerExact();
    } catch (Exception e) {
        return null;
    }
}
 
Example 3
Source File: BalanceUtils.java    From ETHWallet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Base - taken to mean default unit for a currency e.g. ETH, DOLLARS
 * Subunit - taken to mean subdivision of base e.g. WEI, CENTS
 *
 * @param baseAmountStr - decimal amonut in base unit of a given currency
 * @param decimals - decimal places used to convert to subunits
 * @return amount in subunits
 */
public static BigInteger baseToSubunit(String baseAmountStr, int decimals) {
    assert(decimals >= 0);
    BigDecimal baseAmount = new BigDecimal(baseAmountStr);
    BigDecimal subunitAmount = baseAmount.multiply(BigDecimal.valueOf(10).pow(decimals));
    try {
        return subunitAmount.toBigIntegerExact();
    } catch (ArithmeticException ex) {
        assert(false);
        return subunitAmount.toBigInteger();
    }
}
 
Example 4
Source File: TokenTransferProcessor.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(String[] args) {
    TokenTransferReq form = paramsData;
    if (null == form) {
        form = getTokenTransferForm(args);
    }
    String address = form.getAddress();
    String password = CommandHelper.getPwd();
    String contractAddress = form.getContractAddress();
    String url = "/contract/" + contractAddress;
    Result<Map> contract = contractProvider.getContractInfo(new GetContractInfoReq(contractAddress));
    if (contract.isFailed()) {
        return CommandResult.getFailed(contract);
    }
    Boolean isNrc20 = (Boolean) contract.getData().get("nrc20");
    if(!isNrc20) {
        return CommandResult.getFailed("Non-NRC20 contract, can not transfer token.");
    }
    Integer decimals = (Integer) contract.getData().get("decimals");
    BigDecimal amountBigD = new BigDecimal(form.getAmount()).multiply(BigDecimal.TEN.pow(decimals));
    try {
        BigInteger amountBigI = amountBigD.toBigIntegerExact();
        form.setAmount(amountBigI.toString());
    } catch(Exception e) {
        return CommandResult.getFailed("Illegal amount, you can have up to " + decimals + " valid digits after the decimal point.");
    }
    form.setPassword(password);
    Result<String> result = contractProvider.tokenTransfer(form);
    if (result.isFailed()) {
        return CommandResult.getFailed(result);
    }
    return CommandResult.getResult(result);
}
 
Example 5
Source File: BalanceUtils.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
/**
 * Base - taken to mean default unit for a currency e.g. ETH, DOLLARS
 * Subunit - taken to mean subdivision of base e.g. WEI, CENTS
 *
 * @param baseAmountStr - decimal amonut in base unit of a given currency
 * @param decimals - decimal places used to convert to subunits
 * @return amount in subunits
 */
public static BigInteger baseToSubunit(String baseAmountStr, int decimals) {
    assert(decimals >= 0);
    BigDecimal baseAmount = new BigDecimal(baseAmountStr);
    BigDecimal subunitAmount = baseAmount.multiply(BigDecimal.valueOf(10).pow(decimals));
    try {
        return subunitAmount.toBigIntegerExact();
    } catch (ArithmeticException ex) {
        assert(false);
        return subunitAmount.toBigInteger();
    }
}
 
Example 6
Source File: BalanceUtils.java    From Upchain-wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Base - taken to mean default unit for a currency e.g. ETH, DOLLARS
 * Subunit - taken to mean subdivision of base e.g. WEI, CENTS
 *
 * @param baseAmountStr - decimal amonut in base unit of a given currency
 * @param decimals - decimal places used to convert to subunits
 * @return amount in subunits
 */
public static BigInteger baseToSubunit(String baseAmountStr, int decimals) {
    assert(decimals >= 0);
    BigDecimal baseAmount = new BigDecimal(baseAmountStr);
    BigDecimal subunitAmount = baseAmount.multiply(BigDecimal.valueOf(10).pow(decimals));
    try {
        return subunitAmount.toBigIntegerExact();
    } catch (ArithmeticException ex) {
        assert(false);
        return subunitAmount.toBigInteger();
    }
}
 
Example 7
Source File: BalanceUtils.java    From trust-wallet-android-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Base - taken to mean default unit for a currency e.g. ETH, DOLLARS
 * Subunit - taken to mean subdivision of base e.g. WEI, CENTS
 *
 * @param baseAmountStr - decimal amonut in base unit of a given currency
 * @param decimals - decimal places used to convert to subunits
 * @return amount in subunits
 */
public static BigInteger baseToSubunit(String baseAmountStr, int decimals) {
    assert(decimals >= 0);
    BigDecimal baseAmount = new BigDecimal(baseAmountStr);
    BigDecimal subunitAmount = baseAmount.multiply(BigDecimal.valueOf(10).pow(decimals));
    try {
        return subunitAmount.toBigIntegerExact();
    } catch (ArithmeticException ex) {
        assert(false);
        return subunitAmount.toBigInteger();
    }
}
 
Example 8
Source File: BigDecimalTypeDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked" })
public <X> X unwrap(BigDecimal value, Class<X> type, WrapperOptions options) {
	if ( value == null ) {
		return null;
	}
	if ( BigDecimal.class.isAssignableFrom( type ) ) {
		return (X) value;
	}
	if ( BigInteger.class.isAssignableFrom( type ) ) {
		return (X) value.toBigIntegerExact();
	}
	if ( Byte.class.isAssignableFrom( type ) ) {
		return (X) Byte.valueOf( value.byteValue() );
	}
	if ( Short.class.isAssignableFrom( type ) ) {
		return (X) Short.valueOf( value.shortValue() );
	}
	if ( Integer.class.isAssignableFrom( type ) ) {
		return (X) Integer.valueOf( value.intValue() );
	}
	if ( Long.class.isAssignableFrom( type ) ) {
		return (X) Long.valueOf( value.longValue() );
	}
	if ( Double.class.isAssignableFrom( type ) ) {
		return (X) Double.valueOf( value.doubleValue() );
	}
	if ( Float.class.isAssignableFrom( type ) ) {
		return (X) Float.valueOf( value.floatValue() );
	}
	throw unknownUnwrap( type );
}
 
Example 9
Source File: BigDecimalConvertTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * toBigIntegerExact()
 */
public void testToBigIntegerExactException() {
    String a = "-123809648392384754573567356745735.63567890295784902768787678287E-10";
    BigDecimal aNumber = new BigDecimal(a);
    try {
        aNumber.toBigIntegerExact();
        fail("java.lang.ArithmeticException has not been thrown");
    } catch (java.lang.ArithmeticException e) {
        return;
    }
}
 
Example 10
Source File: BigDecimalConvertTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * toBigIntegerExact()
 */
public void testToBigIntegerExact1() {
    String a = "-123809648392384754573567356745735.63567890295784902768787678287E+45";
    BigDecimal aNumber = new BigDecimal(a);
    String res = "-123809648392384754573567356745735635678902957849027687876782870000000000000000";
    BigInteger result = aNumber.toBigIntegerExact();
    assertEquals("incorrect value", res, result.toString());
}
 
Example 11
Source File: Numbers.java    From dekaf with Apache License 2.0 4 votes vote down vote up
@Contract(value = "!null -> !null; null -> null", pure = true)
public static Number convertNumberSmartly(final BigDecimal decimal) {
  if (decimal == null) return null;
  if (decimal.equals(Numbers.DECIMAL_ZERO)) return BYTE_ZERO;

  final int precision = decimal.precision();
  final int scale = decimal.scale();

  Number num;
  if (scale == 0) {
    try {
      if (precision <= 19 && decimal.compareTo(Numbers.DECIMAL_MIN_LONG) >= 0
                          && decimal.compareTo(Numbers.DECIMAL_MAX_LONG) <= 0) {
        long v = decimal.longValueExact();
        if (-128 <= v && v <= 127) num = (byte) v;
        else if (-32768 <= v && v <= 32767) num = (short) v;
        else if (Integer.MIN_VALUE <= v && v <= Integer.MAX_VALUE) num = (int) v;
        else num = v;
      }
      else {
        num = decimal.toBigIntegerExact();
      }
    }
    catch (ArithmeticException ae) {
      num = decimal;
    }
  }
  else {
    if (precision <= 6) {
      num = decimal.floatValue();
    }
    else if (precision <= 15) {
      num = decimal.doubleValue();
    }
    else {
      num = decimal;
    }
  }

  return num;
}
 
Example 12
Source File: BigIntegerCellConverterFactory.java    From xlsmapper with Apache License 2.0 4 votes vote down vote up
@Override
protected BigInteger convertTypeValue(final BigDecimal value) throws NumberFormatException, ArithmeticException {
    BigDecimal decimal = value.setScale(0, RoundingMode.HALF_UP);
    return decimal.toBigIntegerExact();
}
 
Example 13
Source File: TokenTransferProcessor.java    From nuls with MIT License 4 votes vote down vote up
@Override
public CommandResult execute(String[] args) {
    ContractTokenTransfer form = paramsData.get();
    if (null == form) {
        form = getTokenTransferForm(args);
    }
    String address = form.getAddress();
    RpcClientResult res = CommandHelper.getPassword(address, restFul);
    if(!res.isSuccess()){
        return CommandResult.getFailed(res);
    }
    String password = (String)res.getData();

    String contractAddress = form.getContractAddress();
    String url = "/contract/" + contractAddress;
    RpcClientResult checkResult = restFul.get(url, null);
    if (checkResult.isFailed()) {
        return CommandResult.getFailed(checkResult);
    }
    Map<String, Object> data = (Map) checkResult.getData();
    Boolean isNrc20 = (Boolean) data.get("isNrc20");
    if(!isNrc20) {
        return CommandResult.getFailed("Non-NRC20 contract, can not transfer token.");
    }
    Integer decimals = (Integer) data.get("decimals");
    BigDecimal amountBigD = new BigDecimal(form.getAmount()).multiply(BigDecimal.TEN.pow(decimals));
    try {
        BigInteger amountBigI = amountBigD.toBigIntegerExact();
        form.setAmount(amountBigI.toString());
    } catch(Exception e) {
        return CommandResult.getFailed("Illegal amount, you can have up to " + decimals + " valid digits after the decimal point.");
    }

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("address", form.getAddress());
    parameters.put("toAddress", form.getToAddress());
    parameters.put("contractAddress", form.getContractAddress());
    parameters.put("gasLimit", form.getGasLimit());
    parameters.put("price", form.getPrice());
    parameters.put("password", password);
    parameters.put("amount", form.getAmount());
    parameters.put("remark", form.getRemark());
    RpcClientResult result = restFul.post("/contract/token/transfer", parameters);
    if (result.isFailed()) {
        return CommandResult.getFailed(result);
    }
    Map<String, Object> resultMap = MapUtil.createLinkedHashMap(2);
    resultMap.put("txHash", result.getData());
    result.setData(resultMap);
    return CommandResult.getResult(result);
}
 
Example 14
Source File: BigIntType.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public BigInteger get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
        throws SQLException {
    BigDecimal bigDecimal = rs.getBigDecimal(names[0]);
    return bigDecimal != null ? bigDecimal.toBigIntegerExact() : null;
}
 
Example 15
Source File: SimpleNumberFormatter.java    From super-csv-annotation with Apache License 2.0 3 votes vote down vote up
private Number parseFromBigDecimal(final Class<? extends Number> type, final BigDecimal number) {
    
    if(Byte.class.isAssignableFrom(type) || byte.class.isAssignableFrom(type)) {
        return lenient ? number.byteValue() : number.byteValueExact();
        
    } else if(Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type)) {
        return lenient ? number.shortValue() : number.shortValueExact();
        
    } else if(Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
        return lenient ? number.intValue() : number.intValueExact();
        
    } else if(Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) {
        return lenient ? number.longValue() : number.longValueExact();
        
    } else if(Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) {
        return number.floatValue();
        
    } else if(Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
        return number.doubleValue();
        
    } else if(type.isAssignableFrom(BigInteger.class)) {
        return lenient ? number.toBigInteger() : number.toBigIntegerExact();
        
    } else if(type.isAssignableFrom(BigDecimal.class)) {
        return number;
        
    }
    
    throw new IllegalArgumentException(String.format("Not support class type : %s", type.getCanonicalName()));
    
}
 
Example 16
Source File: NumberFormatWrapper.java    From super-csv-annotation with Apache License 2.0 3 votes vote down vote up
private Number convertWithBigDecimal(final Class<? extends Number> type, final BigDecimal number, final String str) {
    
    if(Byte.class.isAssignableFrom(type) || byte.class.isAssignableFrom(type)) {
        return lenient ? number.byteValue() : number.byteValueExact();
        
    } else if(Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type)) {
        return lenient ? number.shortValue() : number.shortValueExact();
        
    } else if(Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
        return lenient ? number.intValue() : number.intValueExact();
        
    } else if(Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) {
        return lenient ? number.longValue() : number.longValueExact();
        
    } else if(Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) {
        return number.floatValue();
        
    } else if(Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
        return number.doubleValue();
        
    } else if(type.isAssignableFrom(BigInteger.class)) {
        return lenient ? number.toBigInteger() : number.toBigIntegerExact();
        
    } else if(type.isAssignableFrom(BigDecimal.class)) {
        return number;
        
    }
    
    throw new IllegalArgumentException(String.format("not support class type : %s", type.getCanonicalName()));
    
}
 
Example 17
Source File: NumberPicker.java    From PhoneProfilesPlus with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the number as currently inputted by the user
 *
 * @return an String representation of the number with no decimal
 */
public BigInteger getNumber() {
    BigDecimal bigDecimal = getEnteredNumber().setScale(0, BigDecimal.ROUND_FLOOR);
    return bigDecimal.toBigIntegerExact();
}