下面列出了怎么用java.math.BigDecimal的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* <p>Set time as one unit, including the optional infinite precison
* fractional seconds.</p>
*
* @param hour value constraints are summarized in
* <a href="#datetimefield-hour">hour field of date/time field mapping table</a>.
* @param minute value constraints are summarized in
* <a href="#datetimefield-minute">minute field of date/time field mapping table</a>.
* @param second value constraints are summarized in
* <a href="#datetimefield-second">second field of date/time field mapping table</a>.
* @param fractional value of <code>null</code> indicates this optional
* field is not set.
*
* @throws IllegalArgumentException if any parameter is
* outside value constraints for the field as specified in
* <a href="#datetimefieldmapping">date/time field mapping table</a>.
*/
public void setTime(
int hour,
int minute,
int second,
BigDecimal fractional) {
setHour(hour, false);
setMinute(minute);
if (second != 60) {
setSecond(second);
} else if ((hour == 23 && minute == 59) || (hour == 0 && minute == 0)) {
setSecond(second);
} else {
invalidFieldValue(SECOND, second);
}
setFractionalSecond(fractional);
// must test hour after setting seconds
testHour();
}
@Override
public BigDecimal getLastYearApprovedECTS() {
ExecutionYear oneYearAgo = readCurrentExecutionYear().getPreviousExecutionYear();
BigDecimal result = BigDecimal.ZERO;
for (final Registration registration : readStudent().getRegistrationsSet()) {
if (registration.isBolonha() && registration.hasAnyCurriculumLines(oneYearAgo)) {
result =
result.add(
calculateApprovedECTS(registration.getLastStudentCurricularPlan().getApprovedCurriculumLines(
oneYearAgo.getFirstExecutionPeriod()))).add(
calculateApprovedECTS(registration.getLastStudentCurricularPlan().getApprovedCurriculumLines(
oneYearAgo.getLastExecutionPeriod())));
}
}
return result;
}
/**
* @param cgPaymentHistoryReportEntry
* @param reportDetail
*/
protected void setReportDate(ContractsGrantsPaymentHistoryReport cgPaymentHistoryReportEntry, ContractsGrantsPaymentHistoryReportDetailDataHolder reportDetail) {
reportDetail.setPaymentNumber(cgPaymentHistoryReportEntry.getPaymentNumber());
reportDetail.setPaymentDate(cgPaymentHistoryReportEntry.getPaymentDate());
reportDetail.setCustomerNumber(cgPaymentHistoryReportEntry.getCustomerNumber());
reportDetail.setCustomerName(cgPaymentHistoryReportEntry.getCustomerName());
BigDecimal paymentAmount = (ObjectUtils.isNull(cgPaymentHistoryReportEntry.getPaymentAmount())) ? BigDecimal.ZERO : cgPaymentHistoryReportEntry.getPaymentAmount().bigDecimalValue();
reportDetail.setPaymentAmount(paymentAmount);
reportDetail.setInvoiceNumber(cgPaymentHistoryReportEntry.getInvoiceNumber());
BigDecimal invoiceAmount = (ObjectUtils.isNull(cgPaymentHistoryReportEntry.getInvoiceAmount())) ? BigDecimal.ZERO : cgPaymentHistoryReportEntry.getInvoiceAmount().bigDecimalValue();
reportDetail.setInvoiceAmount(invoiceAmount);
reportDetail.setAwardNumber(cgPaymentHistoryReportEntry.getAwardNumber().toString());
reportDetail.setReversedIndicator(cgPaymentHistoryReportEntry.isReversedIndicator() ? "Yes" : "No");
reportDetail.setAppliedIndicator(cgPaymentHistoryReportEntry.isAppliedIndicator() ? "Yes" : "No");
}
@Override
public BigDecimal toBigDecimal(int index) throws SFException
{
String str = toString(index);
try
{
if (str == null)
{
return null;
}
else
{
return new BigDecimal(str);
}
}
catch (Exception ex)
{
throw new SFException(ErrorCode.INVALID_VALUE_CONVERT,
logicalTypeStr,
SnowflakeUtil.BIG_DECIMAL_STR,
str);
}
}
@RequestMapping("changeCartNum")
public String changeCartNum(Integer id, Integer num, Model model, HttpSession session) throws Exception {
User user = (User) session.getAttribute("user");
CartItem cartItemFromDB = (CartItem) cartItemService.get(id);
String msg = "fail";
checkUser(user, cartItemFromDB.getUser());
if (cartItemFromDB.getProduct().getStock() >= num) {
cartItemFromDB.setNumber(num);
cartItemFromDB.setSum(cartItemFromDB.getProduct()
.getNowPrice().multiply(new BigDecimal(num)));
cartItemService.update(cartItemFromDB);
msg = "success";
}
model.addAttribute("msg", msg);
return "msg";
}
private InAppProduct JSONObjectToInapp(JSONObject object) {
InAppProduct product = new InAppProduct();
product.productId = object.optString("productId");
//String type = object.optString("type");
product.localizedPrice = object.optString("price");
product.title = object.optString("title");
product.description = object.optString("description");
String price;
if (object.has("price_amount_micros")) {
price = String.valueOf(((float) object.optInt("price_amount_micros")) / 1000000);
} else {
String tmpPrice = product.localizedPrice.replace(",", ".");
price = String.valueOf(tmpPrice.replace(',', '.').substring(0, tmpPrice.length() - 2));
}
product.price = new BigDecimal(price).doubleValue();
return product;
}
/**
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
*
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
*/
@Test
public void testEndpointParametersTest() {
BigDecimal number = null;
Double _double = null;
String patternWithoutDelimiter = null;
byte[] _byte = null;
Integer integer = null;
Integer int32 = null;
Long int64 = null;
Float _float = null;
String string = null;
File binary = null;
LocalDate date = null;
OffsetDateTime dateTime = null;
String password = null;
String paramCallback = null;
// api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback);
// TODO: test validations
}
/**
* Receives notification that a row of data is being processed. Reads the data from the field defined for this
* function and adds it to the running total.
* <P>
* This function assumes that it will find an instance of the Number class in the column of the data-row specified by
* the field name.
*
* @param event
* Information about the event.
*/
public void itemsAdvanced( final ReportEvent event ) {
final Object fieldValue = getDataRow().get( getField() );
if ( fieldValue == null ) {
return;
}
if ( fieldValue instanceof Number == false ) {
return;
}
final Number numerValue = (Number) fieldValue;
final BigDecimal number = ExpressionUtilities.convertToBigDecimal( numerValue );
final BigDecimal oldValue = sum.get( lastGroupSequenceNumber );
if ( oldValue == null ) {
sum.set( lastGroupSequenceNumber, number );
} else {
sum.set( lastGroupSequenceNumber, oldValue.add( number ) );
}
}
public static final void reportSuccess(final long numOfDistinctStates, final long actualDistance,
final long numOfGenStates) throws IOException {
// Prevent div-by-zero when calculating collision probabilities when no states
// are generated.
if (numOfDistinctStates == numOfGenStates && numOfGenStates == 0) {
// When the number of states is zero, printing a collision probability is
// useless anyway. But the Toolbox will probably crash if omitted.
MP.printMessage(EC.TLC_SUCCESS, new String[] { "val = 0.0", "val = 0.0" });
return;
}
// shown as 'calculated' in Toolbox
final String optimisticProbStr = "val = "
+ ProbabilityToString(calculateOptimisticProbability(numOfDistinctStates, numOfGenStates), 2);
// shown as 'observed' in Toolbox
final BigDecimal actualProb = BigDecimal.valueOf(1d).divide(BigDecimal.valueOf(actualDistance),
new MathContext(2));
final String actualProbStr = "val = " + ProbabilityToString(actualProb.doubleValue(), 2);
MP.printMessage(EC.TLC_SUCCESS, new String[] { optimisticProbStr, actualProbStr });
}
/**
* Creates a subscription based on period MONTH, creates parameter for it
* and checks the pricing. All parameter data types are covered.
*
* @throws Exception
*/
@Test
public void testSimplePeriod1BeginOfJanuary() throws Exception {
final int testMonth = Calendar.JANUARY;
final int testDay = 1;
// costs for options will be for enumeration parameter, not price for
// parameter
final BigDecimal parametersAndOptionsCosts = new BigDecimal(5200)
.setScale(BIGDECIMAL_SCALE);
BigDecimal durationParamCosts = getDurationParamCosts(1300, 1,
BigDecimal.ONE);
// with all factors and multipliers no error situation
testSimplePeriod1BeginOfJanuaryBase(testMonth, testDay,
parametersAndOptionsCosts.add(durationParamCosts).setScale(
PriceConverter.NORMALIZED_PRICE_SCALING,
RoundingMode.HALF_UP),
"");
xmlValidator.validateBillingResultXML();
}
public Pair<Transaction, Integer> createArbitraryTransaction(PrivateKeyAccount creator, int service, byte[] data, BigDecimal fee)
{
//CHECK FOR UPDATES
this.checkUpdate();
//TIME
long time = NTP.getTime();
//CREATE SIGNATURE
byte[] signature = ArbitraryTransaction.generateSignature(this.fork, creator, service, data, fee, time);
//CREATE ARBITRARY TRANSACTION
ArbitraryTransaction arbitraryTransaction = new ArbitraryTransaction(creator, service, data, fee, time, creator.getLastReference(this.fork), signature);
//VALIDATE AND PROCESS
return this.afterCreate(arbitraryTransaction);
}
/**
* 本地签名获取tx_blob
* @param account 交易账号
* @param to 接受账号
* @param amountInfo 金额
* @param memos 备注
* @param secret 交易账号私钥
* @param sequence 序列 通过 AccountInfo ainfo = remote.requestAccountInfo(account, null, "trust");获取
* sequence = ainfo.getAccountData().getSequence();
* @return
*/
public static String sign(String account, String to, AmountInfo amountInfo, List<String> memos, String secret,
Integer sequence) {
Payment payment = new Payment();
payment.as(AccountID.Account, account);
payment.as(AccountID.Destination, to);
Object value = toAmount(amountInfo);
if (Value.typeOf(value) == Value.STRING) {// 基础货币 swt
payment.as(Amount.Amount, value);
} else {// 非基础货币
BigDecimal jine = new BigDecimal(amountInfo.getValue());
Amount amount = new Amount(jine, Currency.fromString(amountInfo.getCurrency()),
AccountID.fromString(amountInfo.getIssuer()));
payment.as(Amount.Amount, amount);
}
payment.as(Amount.Fee, String.valueOf(Config.FEE));
payment.sequence(new UInt32(sequence));
payment.flags(new UInt32(0));
payment.addMemo(memos);
SignedTransaction tx = payment.sign(secret);
String tx_blob = tx.tx_blob;
return tx_blob;
}
public void testValidateValue( ) throws PropertyValueException
{
assertEquals( null, type.validateValue( design, null, propDefn, null ) );
assertEquals( null, type.validateValue( design, null, propDefn, "" ) ); //$NON-NLS-1$
assertEquals( 12.34d, ( (Double) type.validateValue( design, null,
propDefn, new Double( 12.34d ) ) ).doubleValue( ), 2 );
assertEquals( 12.34d, ( (Double) type.validateValue( design, null,
propDefn, new Float( 12.34f ) ) ).doubleValue( ), 2 );
assertEquals( 12.34d, ( (Double) type.validateValue( design, null,
propDefn, new BigDecimal( 12.34 ) ) ).doubleValue( ), 2 );
assertEquals( 12, ( (Double) type.validateValue( design, null,
propDefn, new Integer( 12 ) ) ).intValue( ) );
assertEquals( 1, ( (Double) type.validateValue( design, null, propDefn,
new Boolean( true ) ) ).intValue( ) );
assertEquals( 0, ( (Double) type.validateValue( design, null, propDefn,
new Boolean( false ) ) ).intValue( ) );
// String
ThreadResources.setLocale( ULocale.ENGLISH );
assertEquals( 1234.123d, ( (Double) type.validateValue( design, null,
propDefn, "1,234.123" ) ).doubleValue( ), 3 ); //$NON-NLS-1$
assertEquals( 1234.123d, ( (Double) type.validateValue( design, null,
propDefn, "1234.123" ) ).doubleValue( ), 3 ); //$NON-NLS-1$
}
@Override
public AvailableStep withWeight(final BigDecimal weight) {
final long grams = weight.setScale(ZERO, RoundingMode.HALF_UP).longValueExact();
if (doesNotEqual(shopifyVariant.getGrams(), grams)) {
shopifyVariant.setGrams(grams);
changed = true;
}
return this;
}
@Test
public void givenBeanWithNegativeFields_shouldNotValidate() {
Numbers numbers = new Numbers();
numbers.setABigDecimal(BigDecimal.valueOf(-1));
numbers.setAPrimitiveNumber(-5);
LongAdder longAdder = new LongAdder();
longAdder.add(-5);
numbers.setALongAdder(longAdder);
Set<ConstraintViolation<Numbers>> constraintViolations = validator.validate(numbers);
assertThat(constraintViolations.size()).isEqualTo(3);
}
/**
* Create a new ID, using a BigDecimal input. Uses
* {@link BigDecimal#toPlainString()} to generate the string representation.
*/
public IdType(BigDecimal thePid) {
if (thePid != null) {
setValue(toPlainStringWithNpeThrowIfNeeded(thePid));
} else {
setValue(null);
}
}
/**
* 计算delta(变动)部分在积分块中的所占成本
*
* @param rec 积分块
* @param delta 变动部分
* @return 所占成本
*/
public BigDecimal accountCost(PointRecPo rec, BigDecimal delta) {
BigDecimal cost = DecimalUtils.ZERO;
if (rec.getTotalCost() == null
|| DecimalUtils.lte(rec.getTotalCost(), DecimalUtils.ZERO)) { // 积分块没有成本时直接返回0
return cost;
} else if (DecimalUtils.lte(rec.getAvailable(), delta)) { // 不够抵扣时返回剩余的全部
cost = this.getAvailableCost(rec);
} else { // 按比例计算
cost = delta.multiply(rec.getTotalCost()).divide(rec.getTotal())
.setScale(DecimalUtils.SCALE_2, RoundingMode.HALF_UP);
}
return cost;
}
@Test
public void testParse() throws ParsingException {
assertNull(type.parse(null));
assertEquals(BigDecimal.ZERO, type.parse("0"));
assertEquals(BigDecimal.ONE, type.parse("1"));
assertEquals(new BigDecimal("12.34567"), type.parse("12.34567"));
assertEquals(new BigDecimal("-300.724578"), type.parse("-300.724578"));
}
private String getGiftSupplier(final String sku, final ShoppingCart cart, final BigDecimal qty) {
final long shopId = cart.getShoppingContext().getCustomerShopId();
final Map<String, Warehouse> warehouses = warehouseService.getByShopIdMapped(shopId, false);
for (final Warehouse warehouse : warehouses.values()) {
final SkuWarehouse inventory = inventoryResolver.findByWarehouseSku(warehouse, sku);
if (inventory != null && inventory.isAvailableToSell(qty, true)) {
return warehouse.getCode();
}
}
return null;
}
public BigDecimal convertF(BigDecimal temp) {
if (this.scale.equals("C")) {
return cToF(temp);
}
return temp;
}
/**
* 创建 债权标 虚拟产品
* @param repay
* @return
*/
public Product generateVirtualProduct(Repay repay) throws Exception{
Boolean existsFlag = false;
Product virtualProcut = new Product();
try{
List<Product> lists = productService.findByStatusIn(Product.Status.YLTX_CREDIT_PROCD);
if(lists!=null && lists.size()>0){
virtualProcut = lists.get(0);
existsFlag = true;
}
}catch(Exception e){ existsFlag = false; }
if(!existsFlag){
virtualProcut.setRepay(repay);
virtualProcut.setName("债权转让产品");
virtualProcut.setCode("00");
virtualProcut.setAmount("0");
virtualProcut.setPeriod("0");
virtualProcut.setRate("0");
virtualProcut.setDeadline(0);
virtualProcut.setManageFee(BigDecimal.ZERO);
virtualProcut.setManageFeeType("");
virtualProcut.setStatus(Product.Status.YLTX_CREDIT_PROCD);
virtualProcut.setStartingAmt(new BigDecimal("1"));
virtualProcut.setDescription("易联标虚拟产品配置初始化");
Product savedProduct= productService.save(virtualProcut);
if(savedProduct !=null){
Logger.info("易联标虚拟产品配置初始化成功");
virtualProcut = savedProduct;
// 设置产品对应的 费率
initCreditRate(savedProduct, new BigDecimal(HermesConstants.YLTX_CREDIT_LEND_FEE), Rate.RateType.LOAN);
initCreditRate(savedProduct, new BigDecimal(HermesConstants.YLTX_CREDIT_RISK_FEE), Rate.RateType.RISK);
}
}
return virtualProcut;
}
public static String formatBigLn(BigDecimal f) {
if (f == null) {
return "null";
} else if (MathTools.isZero(f)) {
return "0";
} else {
MathContext mathContext = new MathContext(16, RoundingMode.HALF_UP);
BoltzmannCalculator bcalc = new BoltzmannCalculator(mathContext);
return String.format("%9.4f", bcalc.ln1p(f));
}
}
protected InvoiceLineGenerator(
Invoice invoice,
Product product,
String productName,
BigDecimal price,
BigDecimal inTaxPrice,
BigDecimal priceDiscounted,
String description,
BigDecimal qty,
Unit unit,
TaxLine taxLine,
int sequence,
BigDecimal discountAmount,
int discountTypeSelect,
BigDecimal exTaxTotal,
BigDecimal inTaxTotal,
boolean isTaxInvoice) {
this(invoice, product, productName, description, qty, unit, sequence, isTaxInvoice);
this.price = price;
this.inTaxPrice = inTaxPrice;
this.priceDiscounted = priceDiscounted;
this.taxLine = taxLine;
this.discountTypeSelect = discountTypeSelect;
this.discountAmount = discountAmount;
this.exTaxTotal = exTaxTotal;
this.inTaxTotal = inTaxTotal;
}
public BigDecimal getMin() {
return this.min;
}
public Criteria andWeightIn(List<BigDecimal> values) {
addCriterion("weight in", values, "weight");
return (Criteria) this;
}
public BigDecimal getReboundMargin() {
return reboundMargin;
}
@Test
public void testDecimalAveraging() throws Exception {
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(false);
try {
String ddl = "CREATE TABLE IF NOT EXISTS testDecimalArithmatic" +
" (pk VARCHAR NOT NULL PRIMARY KEY, col1 DECIMAL(31, 11), col2 DECIMAL(31,1), col3 DECIMAL(38,1))";
createTestTable(getUrl(), ddl);
String query = "UPSERT INTO testDecimalArithmatic(pk, col1, col2, col3) VALUES(?,?,?,?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, "1");
stmt.setBigDecimal(2, new BigDecimal("99999999999999999999.1"));
stmt.setBigDecimal(3, new BigDecimal("99999999999999999999.1"));
stmt.setBigDecimal(4, new BigDecimal("9999999999999999999999999999999999999.1"));
stmt.execute();
conn.commit();
stmt.setString(1, "2");
stmt.setBigDecimal(2, new BigDecimal("0"));
stmt.setBigDecimal(3, new BigDecimal("0"));
stmt.setBigDecimal(4, new BigDecimal("0"));
stmt.execute();
conn.commit();
stmt.setString(1, "3");
stmt.setBigDecimal(2, new BigDecimal("0"));
stmt.setBigDecimal(3, new BigDecimal("0"));
stmt.setBigDecimal(4, new BigDecimal("0"));
stmt.execute();
conn.commit();
// Averaging
// result scale should be: max(max(ls, rs), 4).
// We are not imposing restriction on precisioin.
query = "SELECT avg(col1) FROM testDecimalArithmatic";
stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
assertTrue(rs.next());
BigDecimal result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("33333333333333333333.03333333333"), result);
query = "SELECT avg(col2) FROM testDecimalArithmatic";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("33333333333333333333.0333"), result);
// We cap our decimal to a precision of 38.
query = "SELECT avg(col3) FROM testDecimalArithmatic";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
assertTrue(rs.next());
result = rs.getBigDecimal(1);
assertEquals(new BigDecimal("3333333333333333333333333333333333333"), result);
} finally {
conn.close();
}
}
public void setJustNumber(BigDecimal justNumber) {
this.justNumber = justNumber;
}
public BigDecimal getRefundFee() {
return refundFee;
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}