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

The following examples show how to use java.math.BigDecimal#valueOf() . 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: FluxResultMapper.java    From influxdb-client-java with MIT License 6 votes vote down vote up
private BigDecimal toBigDecimalValue(final Object value) {
    if (String.class.isAssignableFrom(value.getClass())) {
        return new BigDecimal((String) value);
    }

    if (double.class.isAssignableFrom(value.getClass()) || Double.class.isAssignableFrom(value.getClass())) {
        return BigDecimal.valueOf((double) value);
    }

    if (int.class.isAssignableFrom(value.getClass()) || Integer.class.isAssignableFrom(value.getClass())) {
        return BigDecimal.valueOf((int) value);
    }

    if (long.class.isAssignableFrom(value.getClass()) || Long.class.isAssignableFrom(value.getClass())) {
        return BigDecimal.valueOf((long) value);
    }

    String message = String.format("Cannot cast %s [%s] to %s.",
            value.getClass().getName(), value, BigDecimal.class);

    throw new ClassCastException(message);
}
 
Example 2
Source File: ExchangeServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotAddExtPrebidEventsWhenEventsServiceReturnsEmptyEventsService() {
    // given
    final BigDecimal price = BigDecimal.valueOf(2.0);
    givenBidder(BidderSeatBid.of(
            singletonList(BidderBid.of(
                    Bid.builder().id("bidId").price(price)
                            .ext(mapper.valueToTree(singletonMap("bidExt", 1))).build(), banner, null)),
            emptyList(),
            emptyList()));

    final BidRequest bidRequest = givenBidRequest(givenSingleImp(singletonMap("someBidder", 1)),
            bidRequestBuilder -> bidRequestBuilder.app(App.builder()
                    .publisher(Publisher.builder().id("1001").build()).build()));

    // when
    final BidResponse bidResponse = exchangeService.holdAuction(givenRequestContext(bidRequest)).result();

    // then
    assertThat(bidResponse.getSeatbid()).hasSize(1)
            .flatExtracting(SeatBid::getBid)
            .extracting(bid -> toExtPrebid(bid.getExt()).getPrebid().getEvents())
            .containsNull();
}
 
Example 3
Source File: Calculator.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public Vertex cosh(Vertex source, Vertex left) {
	if ((left.getData() instanceof Number)) {
		try {
			double result = java.lang.Math.cosh((((Number)left.getData()).doubleValue()));
			if (Double.isInfinite(result)) {
				return left.getNetwork().createVertex(Primitive.INFINITY);				
			}
			BigDecimal decimal = BigDecimal.valueOf(result);
			return left.getNetwork().createVertex(checkInteger(decimal));
		} catch (Exception failed) {
			return left.getNetwork().createVertex(Primitive.UNDEFINED);
		}
	}
	if (left.is(Primitive.UNDEFINED)) {
		return left;
	}
	if (left.is(Primitive.INFINITY) || left.is(Primitive.NINFINITY)) {
		return left.getNetwork().createVertex(Primitive.UNDEFINED);
	}
	return left.getNetwork().createVertex(Primitive.NULL);
}
 
Example 4
Source File: ContractDemo.java    From web3j_demo with Apache License 2.0 6 votes vote down vote up
private void sendFunds(Greeter contract) throws Exception {
	System.out.println("// Send 0.05 Ethers to contract");
	
	// trasfer ether to contract account
	String contractAddress = contract.getContractAddress();
	BigDecimal amountEther = BigDecimal.valueOf(0.05);
	BigInteger amountWei = Web3jUtils.etherToWei(amountEther);
	Web3jUtils.transferFromCoinbaseAndWait(web3j, contractAddress, amountWei);			

	// check current # of deposits and balance
	Uint256 deposits = contract
			.deposits()
			.get();

	System.out.println("Contract address balance (after funding): " + Web3jUtils.weiToEther(Web3jUtils.getBalanceWei(web3j, contractAddress)));
	System.out.println("Contract.deposits(): " + deposits.getValue() + "\n");
}
 
Example 5
Source File: CCSystem.java    From FCMFrame with Apache License 2.0 6 votes vote down vote up
private BigDecimal findScale(double num) {
    int x = (int) Math.floor(Math.log10(num));
    
    BigDecimal scale;
    try {
        scale = BigDecimal.TEN.pow(x, prec);
    } catch (ArithmeticException e) {
        scale = BigDecimal.valueOf(Double.MAX_VALUE);
    }
    
    /* Don't need more than double precision here */
    double quot = num / scale.doubleValue();
    if (quot > 5.0) return scale.multiply(BigDecimal.TEN, prec);
    if (quot > 2.0) return scale.multiply(BigDecimal.valueOf(5), prec);
    if (quot > 1.0) return scale.multiply(BigDecimal.valueOf(2), prec);
    else return scale;
}
 
Example 6
Source File: EmployeeRepository.java    From JavaMainRepo with Apache License 2.0 6 votes vote down vote up
protected Employee getEntityFromXmlElement(Element element) {
	String discriminant = element.getElementsByTagName(Constants.XML_TAGS.DISCRIMINANT).item(0).getTextContent();
	switch (discriminant) {
	case Constants.Employees.Caretaker:

		String name = element.getElementsByTagName("name").item(0).getTextContent();
		BigDecimal salary = BigDecimal
				.valueOf(Double.valueOf(element.getElementsByTagName("salary").item(0).getTextContent()));
		long id = Long.valueOf(element.getElementsByTagName("id").item(0).getTextContent());

		Employee caretaker = new Caretaker(name, id, salary);
		caretaker.decodeFromXml(element);
		return caretaker;
	default:
		break;
	}
	return null;
}
 
Example 7
Source File: ROUND_TO.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * java level API
 * @param input expects a numeric value to round, a number of digits to keep, and an optional rounding mode.
 * @return output returns a single numeric value, the number with only those digits retained
 */
@Override
public Double exec(Tuple input) throws IOException {
    if (input == null || input.size() < 2)
        return null;

    try {
        Double       num    = DataType.toDouble(input.get(0));
        Integer      digits = DataType.toInteger(input.get(1));
        RoundingMode mode   = (input.size() >= 3) ?
            RoundingMode.valueOf(DataType.toInteger(input.get(2))) : RoundingMode.HALF_EVEN;
        if (num == null) return null;

        BigDecimal bdnum  = BigDecimal.valueOf(num);
        bdnum = bdnum.setScale(digits, mode);
        return bdnum.doubleValue();
    } catch (NumberFormatException nfe){
        System.err.println("Failed to process input; error - " + nfe.getMessage());
        return null;
    } catch (Exception e){
        throw new IOException("Caught exception processing input row ", e);
    }
}
 
Example 8
Source File: Calculator.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public Vertex floor(Vertex source, Vertex left) {
	if ((left.getData() instanceof Number)) {
		try {
			double result = java.lang.Math.floor((((Number)left.getData()).doubleValue()));
			if (Double.isInfinite(result)) {
				return left.getNetwork().createVertex(Primitive.INFINITY);				
			}
			BigDecimal decimal = BigDecimal.valueOf(result);
			return left.getNetwork().createVertex(checkInteger(decimal));
		} catch (Exception failed) {
			return left.getNetwork().createVertex(Primitive.UNDEFINED);
		}
	}
	if (left.is(Primitive.UNDEFINED)) {
		return left;
	}
	if (left.is(Primitive.INFINITY) || left.is(Primitive.NINFINITY)) {
		return left.getNetwork().createVertex(Primitive.INFINITY);
	}
	return left.getNetwork().createVertex(Primitive.NULL);
}
 
Example 9
Source File: AppendIT.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Create data for the first hop.
 */
public List<RowMetaAndData> createData1() {
  List<RowMetaAndData> list = new ArrayList<RowMetaAndData>();

  RowMetaInterface rm = createRowMetaInterface();

  Object[] r1 =
    new Object[] {
      "KETTLE1", new Long( 123L ), new Double( 10.5D ), new Date(), Boolean.TRUE,
      BigDecimal.valueOf( 123.45 ), BigDecimal.valueOf( 123.60 ) };
  Object[] r2 =
    new Object[] {
      "KETTLE1", new Long( 500L ), new Double( 20.0D ), new Date(), Boolean.FALSE,
      BigDecimal.valueOf( 123.45 ), BigDecimal.valueOf( 123.60 ) };
  Object[] r3 =
    new Object[] {
      "KETTLE1", new Long( 501L ), new Double( 21.0D ), new Date(), Boolean.FALSE,
      BigDecimal.valueOf( 123.45 ), BigDecimal.valueOf( 123.70 ) };

  list.add( new RowMetaAndData( rm, r1 ) );
  list.add( new RowMetaAndData( rm, r2 ) );
  list.add( new RowMetaAndData( rm, r3 ) );

  return list;
}
 
Example 10
Source File: NumberUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static BigDecimal toBigDecimal(Number number) {
  if (number == null) {
    return null;
  }
  if (number instanceof BigDecimal) {
    return (BigDecimal) number;
  } else if ((number instanceof Double)
      || (number instanceof Float)) {
    return BigDecimal.valueOf(number.doubleValue());
  } else if (number instanceof BigInteger) {
    return new BigDecimal((BigInteger) number);
  } else {
    return new BigDecimal(number.longValue());
  }
}
 
Example 11
Source File: BaseController.java    From roncoo-pay with Apache License 2.0 5 votes vote down vote up
public BigDecimal getBigDecimal(String name, BigDecimal defaultValue) {
	String resultStr = getRequest().getParameter(name);
	if (resultStr != null) {
		try {
			return BigDecimal.valueOf(Double.parseDouble(resultStr));
		} catch (Exception e) {
			log.error("参数转换错误:",e);
			return defaultValue;
		}
	}
	return defaultValue;
}
 
Example 12
Source File: CaretakerFactory.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
@Override
public Caretaker getEmployeeFactory(String type) throws Exception {
	if (Constants.Employees.Caretaker.equals(type)) {
		int randomNames = (int) (Math.random() * names.length);
		long randomId = min + (long) (Math.random() * ((max - min) + 1));
		return new Caretaker(names[randomNames], randomId, BigDecimal.valueOf(2000));
	} else {
		throw new Exception("The employee doesn't exist.");
	}
}
 
Example 13
Source File: InformationContentService.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Double load(OntologyWord key) throws ExecutionException {
  String ontologyIri = key.getOntologyIri();
  Entity ontologyEntity =
      dataService.findOne(
          ONTOLOGY,
          new QueryImpl<>().eq(OntologyMetadata.ONTOLOGY_IRI, ontologyIri));
  if (ontologyEntity != null) {
    QueryRule queryRule =
        new QueryRule(
            Arrays.asList(
                new QueryRule(
                    OntologyTermMetadata.ONTOLOGY_TERM_SYNONYM,
                    Operator.FUZZY_MATCH,
                    key.getWord())));
    queryRule.setOperator(Operator.DIS_MAX);
    QueryRule finalQuery =
        new QueryRule(
            Arrays.asList(
                new QueryRule(
                    OntologyTermMetadata.ONTOLOGY, Operator.EQUALS, ontologyEntity),
                new QueryRule(Operator.AND),
                queryRule));
    long wordCount = dataService.count(ONTOLOGY_TERM, new QueryImpl<>(finalQuery));
    Long total = cachedTotalWordCount.get(ontologyIri);
    BigDecimal idfValue =
        BigDecimal.valueOf(
            total == null ? 0 : (1 + Math.log((double) total / (wordCount + 1))));
    return idfValue.doubleValue();
  }
  return (double) 0;
}
 
Example 14
Source File: MixedJavaTimeFEELLib.java    From jdmn with Apache License 2.0 5 votes vote down vote up
public BigDecimal day(ZonedDateTime dateTime) {
    try {
        return BigDecimal.valueOf(this.dateLib.day(dateTime));
    } catch (Exception e) {
        String message = String.format("day(%s)", dateTime);
        logError(message, e);
        return null;
    }
}
 
Example 15
Source File: XMLGregorianCalendarImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return result of adding second and fractional second field
 */
private BigDecimal getSeconds() {
    if (second == DatatypeConstants.FIELD_UNDEFINED) {
        return DECIMAL_ZERO;
    }
    BigDecimal result = BigDecimal.valueOf((long) second);
    if (fractionalSecond != null) {
        return result.add(fractionalSecond);
    } else {
        return result;
    }
}
 
Example 16
Source File: Decimal64.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
public final BigDecimal decimalValue() {
    return BigDecimal.valueOf(value, scaleOffset + 1);
}
 
Example 17
Source File: SqlFunctions.java    From Quicksql with MIT License 4 votes vote down vote up
/** SQL <code>SIGN</code> operator applied to BigDecimal values. */
public static BigDecimal sign(BigDecimal b0) {
  return BigDecimal.valueOf(b0.signum());
}
 
Example 18
Source File: DecimalType.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
public DecimalType(double value) {
    this.value = BigDecimal.valueOf(value);
}
 
Example 19
Source File: ValueConverters.java    From morf with Apache License 2.0 4 votes vote down vote up
@Override
public BigDecimal bigDecimalValue(Double value) {
  return BigDecimal.valueOf(value);
}
 
Example 20
Source File: PersistentMoneyMinorAmountAndCurrency.java    From jadira with Apache License 2.0 3 votes vote down vote up
@Override
protected Money fromConvertedColumns(Object[] convertedColumns) {

    CurrencyUnit currencyUnitPart = (CurrencyUnit) convertedColumns[0];
    Long amountMinorPart = (Long) convertedColumns[1];

    BigDecimal majorVal = BigDecimal.valueOf(amountMinorPart, currencyUnitPart.getDefaultFractionDigits());

    return Money.of(majorVal, currencyUnitPart);
}