Example usage for java.math BigDecimal scaleByPowerOfTen

List of usage examples for java.math BigDecimal scaleByPowerOfTen

Introduction

In this page you can find the example usage for java.math BigDecimal scaleByPowerOfTen.

Prototype

public BigDecimal scaleByPowerOfTen(int n) 

Source Link

Document

Returns a BigDecimal whose numerical value is equal to ( this * 10n).

Usage

From source file:Main.java

public static void main(String[] args) {

    BigDecimal bg1 = new BigDecimal("123.000");
    BigDecimal bg2 = new BigDecimal("12300");

    BigDecimal bg3 = bg1.scaleByPowerOfTen(3);
    BigDecimal bg4 = bg2.scaleByPowerOfTen(-3);

    String str1 = bg1 + " raised to 10 power 3 is " + bg3;
    String str2 = bg2 + " raised to 10 power -3 is " + bg4;

    System.out.println(str1);//w  w  w.j  av a2  s.c  o  m
    System.out.println(str2);
}

From source file:Main.java

public static void main(String... args) {
    long base = 12345;
    int scale = 4;

    BigDecimal number = BigDecimal.valueOf(base, scale);
    System.out.println(number);/*w  w w.java  2s .  co m*/
    BigDecimal pointRight = number.movePointRight(5);
    System.out.println(pointRight + "; my scale is " + pointRight.scale());
    BigDecimal scaleBy = number.scaleByPowerOfTen(5);
    System.out.println(scaleBy + "; my scale is " + scaleBy.scale());
}

From source file:com.amazonaws.util.DateUtils.java

/**
 * Formats the give date object into an AWS Service format.
 *//* w  w  w  .j  av a 2  s.c  om*/
public static String formatServiceSpecificDate(Date date) {
    if (date == null)
        return null;
    BigDecimal dateValue = BigDecimal.valueOf(date.getTime());
    return dateValue.scaleByPowerOfTen(0 - AWS_DATE_MILLI_SECOND_PRECISION).toPlainString();
}

From source file:com.amazonaws.util.DateUtils.java

/**
 * Parses the given date string returned by the AWS service into a Date
 * object.//from  www  .  j  av a 2  s .com
 */
public static Date parseServiceSpecificDate(String dateString) {
    if (dateString == null)
        return null;
    try {
        BigDecimal dateValue = new BigDecimal(dateString);
        return new Date(dateValue.scaleByPowerOfTen(AWS_DATE_MILLI_SECOND_PRECISION).longValue());
    } catch (NumberFormatException nfe) {
        throw new AmazonClientException("Unable to parse date : " + dateString, nfe);
    }
}

From source file:de.micromata.genome.util.types.Converter.java

/**
 * Builds the normalized number string.//  w  w  w . j  a v a 2 s . c  om
 *
 * @param nr the nr
 * @param exp10 the exp10
 * @param scale the scale
 * @param decimalChar the decimal char
 * @param unit the unit
 * @return the string
 */
public static String buildNormalizedNumberString(BigDecimal nr, int exp10, int scale, char decimalChar,
        String unit) {
    if (nr == null) {
        return "";
    }
    String str = nr.scaleByPowerOfTen(exp10).setScale(scale, BigDecimal.ROUND_HALF_UP).toPlainString()
            .replace('.', decimalChar);
    if (unit == null) {
        return str;
    }
    return str + " " + unit;
}

From source file:com.coinprism.wallet.fragment.SendTab.java

private void onSend() {
    final String to = toAddress.getText().toString();
    final String unitString = amount.getText().toString();
    final BigDecimal decimalAmount;

    final AssetDefinition selectedAsset = (AssetDefinition) assetSpinner.getSelectedItem();

    final ProgressDialog progressDialog = new ProgressDialog();

    try {/* w w  w.  jav  a  2 s .c o m*/
        decimalAmount = new BigDecimal(unitString);
    } catch (NumberFormatException exception) {
        showError(getString(R.string.tab_send_error_invalid_amount));
        return;
    }

    AsyncTask<Void, Void, Transaction> getTransaction = new AsyncTask<Void, Void, Transaction>() {
        private String subCode;

        protected Transaction doInBackground(Void... _) {
            try {
                SharedPreferences sharedPreferences = PreferenceManager
                        .getDefaultSharedPreferences(SendTab.this.getActivity());

                String value = sharedPreferences.getString(UserPreferences.defaultFeesKey,
                        getString(R.string.default_fees));

                BigDecimal decimal = new BigDecimal(value);
                long fees = decimal.scaleByPowerOfTen(8).toBigInteger().longValue();

                if (selectedAsset == null) {
                    // Send uncolored bitcoins
                    return WalletState.getState().getAPIClient().buildTransaction(
                            WalletState.getState().getConfiguration().getAddress(), to,
                            decimalAmount.scaleByPowerOfTen(8).toBigInteger().toString(), null, fees);
                } else {
                    // Send an asset
                    BigInteger unitAmount = decimalAmount.scaleByPowerOfTen(selectedAsset.getDivisibility())
                            .toBigInteger();
                    return WalletState.getState().getAPIClient().buildTransaction(
                            WalletState.getState().getConfiguration().getAddress(), to, unitAmount.toString(),
                            selectedAsset.getAssetId(), fees);
                }
            } catch (APIException exception) {
                // The API returned an error
                subCode = exception.getSubCode();
                return null;
            } catch (Exception exception) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(Transaction result) {
            super.onPostExecute(result);

            if (!progressDialog.getIsCancelled()) {
                progressDialog.dismiss();
                if (result != null)
                    onConfirm(result, decimalAmount, selectedAsset, to);
                else if (subCode == null)
                    showError(getString(R.string.tab_send_error_connection_error));
                else if (subCode.equals("InsufficientFunds"))
                    showError(getString(R.string.tab_send_error_insufficient_funds));
                else if (subCode.equals("InsufficientColoredFunds"))
                    showError(getString(R.string.tab_send_error_insufficient_asset));
                else if (subCode.equals("AmountUnderDustThreshold")
                        || subCode.equals("ChangeUnderDustThreshold"))
                    showError(getString(R.string.tab_send_error_amount_too_low));
                else
                    showError(getString(R.string.tab_send_error_server_error));
            }
        }
    };

    progressDialog.configure(getString(R.string.tab_send_dialog_please_wait),
            getString(R.string.tab_send_dialog_verifying_balance), true);
    progressDialog.show(this.getActivity().getSupportFragmentManager(), "");

    getTransaction.execute();
}

From source file:com.wicht.benchmark.utils.Benchs.java

private double getExactMean(double mean, Prefix prefix) {
    BigDecimal exactMean = BigDecimal.valueOf(mean);

    exactMean = exactMean.scaleByPowerOfTen(-prefix.getExponent());

    return exactMean.doubleValue();
}

From source file:net.pms.util.Rational.java

/**
 * Returns an instance with the given {@code numerator} and
 * {@code denominator}.//from   w  ww.  j a  v a  2 s  .c om
 *
 * @param numerator the numerator.
 * @param denominator the denominator.
 * @return An instance that represents the value of {@code numerator}/
 *         {@code denominator}.
 */
@Nullable
public static Rational valueOf(@Nullable BigDecimal numerator, @Nullable BigDecimal denominator) {
    if (numerator == null || denominator == null) {
        return null;
    }
    if (numerator.signum() == 0 && denominator.signum() == 0) {
        return NaN;
    }
    if (denominator.signum() == 0) {
        return numerator.signum() > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
    }
    if (numerator.signum() == 0) {
        return ZERO;
    }
    if (numerator.equals(denominator)) {
        return ONE;
    }
    if (denominator.signum() < 0) {
        numerator = numerator.negate();
        denominator = denominator.negate();
    }

    int scale = Math.max(numerator.scale(), denominator.scale());
    if (scale > 0) {
        numerator = numerator.scaleByPowerOfTen(scale);
        denominator = denominator.scaleByPowerOfTen(scale);
    }
    BigInteger biNumerator = numerator.toBigIntegerExact();
    BigInteger biDenominator = denominator.toBigIntegerExact();

    BigInteger reducedNumerator;
    BigInteger reducedDenominator;
    BigInteger greatestCommonDivisor = calculateGreatestCommonDivisor(biNumerator, biDenominator);
    if (BigInteger.ONE.equals(greatestCommonDivisor)) {
        reducedNumerator = biNumerator;
        reducedDenominator = biDenominator;
    } else {
        reducedNumerator = biNumerator.divide(greatestCommonDivisor);
        reducedDenominator = biDenominator.divide(greatestCommonDivisor);
    }
    return new Rational(biNumerator, biDenominator, greatestCommonDivisor, reducedNumerator,
            reducedDenominator);
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The exponential function.//from www  . j a v a  2s .c om
 *
 * @param x the argument.
 * @return exp(x).
 * The precision of the result is implicitly defined by the precision in the argument.
 * 16
 * In particular this means that "Invalid Operation" errors are thrown if catastrophic
 * cancellation of digits causes the result to have no valid digits left.
 */
static public BigDecimal exp(BigDecimal x) {
    /* To calculate the value if x is negative, use exp(-x) = 1/exp(x)
     */
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        final BigDecimal invx = exp(x.negate());
        /* Relative error in inverse of invx is the same as the relative errror in invx.
         * This is used to define the precision of the result.
         */
        MathContext mc = new MathContext(invx.precision());
        return BigDecimal.ONE.divide(invx, mc);
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        /* recover the valid number of digits from x.ulp(), if x hits the
         * zero. The x.precision() is 1 then, and does not provide this information.
         */
        return scalePrec(BigDecimal.ONE, -(int) (Math.log10(x.ulp().doubleValue())));
    } else {
        /* Push the number in the Taylor expansion down to a small
         * value where TAYLOR_NTERM terms will do. If x<1, the n-th term is of the order
         * x^n/n!, and equal to both the absolute and relative error of the result
         * since the result is close to 1. The x.ulp() sets the relative and absolute error
         * of the result, as estimated from the first Taylor term.
         * We want x^TAYLOR_NTERM/TAYLOR_NTERM! < x.ulp, which is guaranteed if
         * x^TAYLOR_NTERM < TAYLOR_NTERM*(TAYLOR_NTERM-1)*...*x.ulp.
         */
        final double xDbl = x.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue();
        if (Math.pow(xDbl, TAYLOR_NTERM) < TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0)
                * xUlpDbl) {
            /* Add TAYLOR_NTERM terms of the Taylor expansion (Eulers sum formula)
             */
            BigDecimal resul = BigDecimal.ONE;
            /* x^i */
            BigDecimal xpowi = BigDecimal.ONE;
            /* i factorial */
            BigInteger ifac = BigInteger.ONE;
            /* TAYLOR_NTERM terms to be added means we move x.ulp() to the right
             * for each power of 10 in TAYLOR_NTERM, so the addition wont add noise beyond
             * whats already in x.
             */
            MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / TAYLOR_NTERM));
            for (int i = 1; i <= TAYLOR_NTERM; i++) {
                ifac = ifac.multiply(new BigInteger("" + i));
                xpowi = xpowi.multiply(x);
                final BigDecimal c = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(c);
                if (Math.abs(xpowi.doubleValue()) < i && Math.abs(c.doubleValue()) < 0.5 * xUlpDbl) {
                    break;
                }
            }
            /* exp(x+deltax) = exp(x)(1+deltax) if deltax is <<1. So the relative error
             * in the result equals the absolute error in the argument.
             */
            MathContext mc = new MathContext(err2prec(xUlpDbl / 2.));
            return resul.round(mc);
        } else {
            /* Compute exp(x) = (exp(0.1*x))^10. Division by 10 does not lead
             * to loss of accuracy.
             */
            int exSc = (int) (1.0 - Math.log10(TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0)
                    * xUlpDbl / Math.pow(xDbl, TAYLOR_NTERM)) / (TAYLOR_NTERM - 1.0));
            BigDecimal xby10 = x.scaleByPowerOfTen(-exSc);
            BigDecimal expxby10 = exp(xby10);
            /* Final powering by 10 means that the relative error of the result
             * is 10 times the relative error of the base (First order binomial expansion).
             * This looses one digit.
             */
            MathContext mc = new MathContext(expxby10.precision() - exSc);
            /* Rescaling the powers of 10 is done in chunks of a maximum of 8 to avoid an invalid operation
            17
             * response by the BigDecimal.pow library or integer overflow.
             */
            while (exSc > 0) {
                int exsub = Math.min(8, exSc);
                exSc -= exsub;
                MathContext mctmp = new MathContext(expxby10.precision() - exsub + 2);
                int pex = 1;
                while (exsub-- > 0) {
                    pex *= 10;
                }
                expxby10 = expxby10.pow(pex, mctmp);
            }
            return expxby10.round(mc);
        }
    }
}