Example usage for java.math BigDecimal valueOf

List of usage examples for java.math BigDecimal valueOf

Introduction

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

Prototype

public static BigDecimal valueOf(double val) 

Source Link

Document

Translates a double into a BigDecimal , using the double 's canonical string representation provided by the Double#toString(double) method.

Usage

From source file:com.sarm.calculatepi.calculator.PiCalculatorImpl.java

/**
 * This method calculates the Pi using the Leibniz formula. 
 * Using the modulus operator it is determined which term are we at, as per the
 * formula, the fraction is added or subtracted. 
 * @param piBean// ww  w  . j av a2  s. co  m
 * @return 
 */
@Override
public PiBean calculatePi(PiBean piBean) {
    logger.debug("   calculatePi ... ");

    double sum = 0;
    for (int i = 0; i < piBean.getApproximation(); i++) {
        if (i % 2 == 0) // if the remainder of `i/2` is 0
        {
            sum = sum + (1.0 / (2.0 * i + 1));
        } else {
            sum = sum - (1.0 / (2.0 * i + 1));
        }
    }
    //        The sum is actually the value of Pi/4 so we have to multiply by 4 to
    //        get Pi
    sum = sum * 4.0;

    piBean.setPiValue(BigDecimal.valueOf(sum));

    return piBean;
}

From source file:com.norconex.commons.wicket.bootstrap.progress.BootstrapProgressBar.java

private static int toPercent(double fraction) {
    return BigDecimal.valueOf(fraction).scaleByPowerOfTen(2).intValue();
}

From source file:org.openmhealth.schema.domain.omh.TypedUnitValue.java

public TypedUnitValue(T typedUnit, double value) {
    this(typedUnit, BigDecimal.valueOf(value));
}

From source file:livhuwani.rambuda.policy_app.services.Impl.PolicyCrudServiceImpl.java

@Override
public Policy createBusinessPolicy(BusinessInterest type) {
    Policy policy = new Policy();
    policy.setId(Long.MAX_VALUE + 1);
    policy.setDescription("Businss Policy");
    policy.setOwnership("100");
    policy.setPolicyNumber("2154635");
    policy.setPolicyValue(BigDecimal.valueOf(1500000));
    policy.setTouchDate(DateTime.now());
    policy.getPolicyType().setBusinessInterest(type);

    Policy savedPolicy = policyRepository.saveAndFlush(policy);
    return savedPolicy;
}

From source file:org.mjunx.LoggerLoadTester.java

@Override
public void run(String... args) throws Exception {
    final Logger logger = LogManager.getLogger();
    final long start = System.nanoTime();
    for (int i = 0; i < ITERATIONS; i++) {
        logger.info("Test log message #{}", i);
    }//ww  w .  ja v  a 2 s  .  co m
    final long duration = System.nanoTime() - start;
    final BigDecimal average = BigDecimal.valueOf(duration).divide(BigDecimal.valueOf(ITERATIONS));
    System.out.append("Average time per operation: ").append(average.toPlainString()).append(" ns.\n");
}

From source file:com.creditcloud.carinsurance.local.CarInsuranceFeeLocalBean.java

/**
 * ?/*from w  ww  .j  a  v  a  2 s . co  m*/
 * @param repayment
 * @return 
 */
public BigDecimal overdueFee(CarInsuranceRepayment repayment) {
    if (repayment == null) {
        return BigDecimal.ZERO;
    }
    if (LocalDate.now().toDate().compareTo(repayment.getDueDate()) <= 0) {
        return BigDecimal.ZERO;
    }
    BigDecimal days = BigDecimal.ZERO;
    //
    if (repayment.getRepayDate() != null) {
        long repayTime = repayment.getRepayDate().getTime();
        long dueTime = repayment.getDueDate().getTime();
        days = BigDecimal.valueOf((repayTime - dueTime) / DateUtils.MILLIS_PER_DAY);
        if (days.compareTo(BigDecimal.ZERO) < 0) {
            return BigDecimal.ZERO;
        }
    } else {
        long nowTime = LocalDate.now().plusDays(1).toDate().getTime();
        long dueTime = repayment.getDueDate().getTime();
        days = BigDecimal.valueOf((nowTime - dueTime) / DateUtils.MILLIS_PER_DAY);
    }
    BigDecimal penaltyAmount = BigDecimal.ZERO;
    //???
    Fee overduePenaltyFee = configManager.getCarInsuranceConfig().getPenaltyFee();
    penaltyAmount = FeeUtils.calculate(overduePenaltyFee, repayment.getAmountPrincipal()).multiply(days)
            .setScale(NumberConstant.DEFAULT_SCALE, NumberConstant.ROUNDING_MODE);
    return penaltyAmount;
}

From source file:com.salatigacode.dao.ProductDaoTests.java

@Test
public void testFindById() {
    Product p = pd.findOne("abc123");
    Assert.assertNotNull(p);/*from   w  ww  . ja  v a2 s.  com*/
    Assert.assertEquals("P-001", p.getCode());
    Assert.assertEquals("Product 001", p.getName());
    Assert.assertEquals(BigDecimal.valueOf(101000.01), p.getPrice());
    Assert.assertNull(pd.findOne("notexist"));
}

From source file:com.livhuwani.rambuda.policyquotationapp.services.Impl.PolicyCrudServiceImpl.java

@Override
public Policy createBusinessPolicy(BusinessInterest type) {
    Policy policy = new Policy();
    policy.setId(Long.MAX_VALUE + 1);
    policy.setDescription("Businss Policy");
    policy.setOwnership("100");
    policy.setPolicyNumber("2154635");
    policy.setPolicyValue(BigDecimal.valueOf(1500000));
    policy.setTouchDate(new Date());
    policy.getPolicyType().setBusinessInterest(type);

    Policy savedPolicy = policyRepository.saveAndFlush(policy);
    return savedPolicy;
}

From source file:de.urszeidler.ethereum.licencemanager1.deployer.LicenseManagerDeployer.java

/**
 * @param args/*w ww .  ja  va  2  s .com*/
 */
public static void main(String[] args) {
    Options options = createOptions();
    CommandLineParser parser = new DefaultParser();
    int returnValue = 0;
    boolean dontExit = false;
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption("h")) {
            printHelp(options);
            return;
        }
        if (commandLine.hasOption("de"))
            dontExit = true;

        String senderKey = null;
        String senderPass = null;
        if (commandLine.hasOption("sk"))
            senderKey = commandLine.getOptionValue("sk");
        if (commandLine.hasOption("sp"))
            senderPass = commandLine.getOptionValue("sp");

        LicenseManagerDeployer manager = new LicenseManagerDeployer();

        try {
            manager.init(senderKey, senderPass);

            long currentMili = 0;
            EthValue balance = null;
            if (commandLine.hasOption("calcDeploymendCost")) {
                currentMili = System.currentTimeMillis();
                balance = manager.ethereum.getBalance(manager.sender);
            }
            if (commandLine.hasOption("observeBlock")) {
                manager.ethereum.events().observeBlocks()
                        .subscribe(b -> System.out.println("Block: " + b.blockNumber + " " + b.receipts));
            }

            if (commandLine.hasOption("f")) {
                String[] values = commandLine.getOptionValues("f");

                String filename = values[0];
                String isCompiled = values[1];
                manager.deployer.setContractSource(filename, Boolean.parseBoolean(isCompiled));
            }
            if (commandLine.hasOption("millis")) {
                manager.setMillis(Long.parseLong(commandLine.getOptionValue("millis")));
            }

            if (commandLine.hasOption("c")) {
                String[] values = commandLine.getOptionValues("c");
                if (values == null || values.length != 2) {
                    System.out.println("Error. Need 2 parameters: paymentAddress,name");
                    System.out.println("");
                    printHelp(options);
                    return;
                }

                String paymentAddress = values[0];
                String name = values[1];
                manager.deployLicenseManager(EthAddress.of(paymentAddress), name);
            } else if (commandLine.hasOption("l")) {
                String contractAddress = commandLine.getOptionValue("l");
                if (contractAddress == null) {
                    System.out.println("Error. Need 1 parameters: contract address");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                manager.setManager(EthAddress.of(contractAddress));
                manager.listContractData(EthAddress.of(contractAddress));
            } else if (commandLine.hasOption("cic")) {
                String[] values = commandLine.getOptionValues("cic");
                if (values == null || values.length != 6) {
                    System.out.println("Error. Need 6 itemName, textHash, url, lifeTime, price");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String contractAddress = values[0];
                String itemName = values[1];
                String textHash = values[2];
                String url = values[3];
                String lifeTime = values[4];
                String price = values[5];

                manager.setManager(EthAddress.of(contractAddress));
                manager.createIssuerContract(itemName, textHash, url, Integer.parseInt(lifeTime),
                        Integer.parseInt(price));
            } else if (commandLine.hasOption("bli")) {
                String[] values = commandLine.getOptionValues("bli");
                if (values == null || values.length < 2 || values.length > 3) {
                    System.out.println(
                            "Error. Need 2-3 issuerAddress, name, optional an address when not use the sender.");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String issuerAddress = values[0];
                String name = values[1];
                String address = values.length > 2 ? values[2] : null;

                manager.buyLicense(issuerAddress, name, address);
            } else if (commandLine.hasOption("v")) {
                String[] values = commandLine.getOptionValues("v");

                String issuerAddress = values[0];
                String message = values[1];
                String signature = values[2];
                String publicKey = values[3];

                manager.verifyLicense(issuerAddress, message, signature, publicKey);
            } else if (commandLine.hasOption("cs")) {
                String message = commandLine.getOptionValue("cs");
                if (message == null) {
                    System.out.println("Error. Need 1 parameter: message");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String signature = createSignature(manager.sender, message);
                String publicKeyString = toPublicKeyString(manager.sender);
                System.out.println("The signature for the message is:");
                System.out.println(signature);
                System.out.println("The public key is:");
                System.out.println(publicKeyString);
            } else if (commandLine.hasOption("co")) {
                String[] values = commandLine.getOptionValues("co");
                if (values == null || values.length != 2) {
                    System.out.println("Error. Need 2 parameters: contractAddress, newOwnerAddress");
                    System.out.println("");
                    printHelp(options);
                    return;
                }

                String contractAddress = values[0];
                String newOwner = values[1];

                manager.changeOwner(EthAddress.of(contractAddress), EthAddress.of(newOwner));
            } else if (commandLine.hasOption("si")) {
                String contractAddress = commandLine.getOptionValue("si");
                if (contractAddress == null) {
                    System.out.println("Error. Need 1 parameters: contract address");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                manager.setManager(EthAddress.of(contractAddress));
                manager.stopIssue(contractAddress);
            } else if (commandLine.hasOption("ppuk")) {
                System.out.println("Public key: " + toPublicKeyString(manager.sender));
            }

            if (manager.licenseManager != null && commandLine.hasOption("wca")) {
                String[] values = commandLine.getOptionValues("wca");
                String filename = values[0];

                File file = new File(filename);
                IOUtils.write(
                        !commandLine.hasOption("cic") ? manager.licenseManager.contractAddress.withLeading0x()
                                : manager.licenseManager.contractInstance
                                        .contracts(manager.licenseManager.contractInstance.contractCount() - 1)
                                        .withLeading0x(),
                        new FileOutputStream(file), "UTF-8");
            }

            if (commandLine.hasOption("calcDeploymendCost")) {
                balance = balance.minus(manager.ethereum.getBalance(manager.sender));
                BigDecimal divide = new BigDecimal(balance.inWei())
                        .divide(BigDecimal.valueOf(1_000_000_000_000_000_000L));

                System.out.println("Deployment cost: " + (divide) + " in wei:" + balance.inWei()
                        + " time need: " + (System.currentTimeMillis() - currentMili));
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            printHelp(options);
            returnValue = 10;
        }

    } catch (ParseException e1) {
        System.out.println(e1.getMessage());
        printHelp(options);
        returnValue = 10;
    }
    if (!dontExit)
        System.exit(returnValue);
}

From source file:org.openmhealth.schema.domain.omh.TypedUnitValue.java

public TypedUnitValue(T typedUnit, long value) {
    this(typedUnit, BigDecimal.valueOf(value));
}