当前位置: 首页>>代码示例>>Java>>正文


Java RoundingMode类代码示例

本文整理汇总了Java中java.math.RoundingMode的典型用法代码示例。如果您正苦于以下问题:Java RoundingMode类的具体用法?Java RoundingMode怎么用?Java RoundingMode使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


RoundingMode类属于java.math包,在下文中一共展示了RoundingMode类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: UserKDRRecordStats

import java.math.RoundingMode; //导入依赖的package包/类
public UserKDRRecordStats(long recordCount, long kills, long deaths, long suicides, User favoriteTarget) {
  super(recordCount, deaths, kills);
  this.suicides = suicides;
  this.favoriteTarget = favoriteTarget;

  // The KDR ratio as KILLS/DEATHS/SUICIDES
  String suicideRatio;
  if (suicides > 0) {
    suicideRatio = new BigDecimal((double) losses / (double) suicides)
        .setScale(1, RoundingMode.HALF_UP)
        .toString();
  } else {
    suicideRatio = "0";
  }

  this.kdr = MathUtils.asFraction(wins, losses) + '/' + suicideRatio;
}
 
开发者ID:Juraji,项目名称:Biliomi,代码行数:18,代码来源:UserKDRRecordStats.java

示例2: testGlobal

import java.math.RoundingMode; //导入依赖的package包/类
@Test // tested: All
public void testGlobal() {
  Map<String, AddOnNotionalFactor> factors = new HashMap<>();
  factors.put(AN1.getProduct(), AN1);
  factors.put(AN2.getProduct(), AN2);
  Map<String, List<AddOnNotional>> notional = new HashMap<>();
  notional.put(AN3.getProduct(), Arrays.asList(AN3, AN4, AN5));
  notional.put(AN6.getProduct(), Arrays.asList(AN6, AN7));
  notional.put(AN8.getProduct(), Arrays.asList(AN8));
  notional.put(AN9.getProduct(), Arrays.asList(AN9));
  Map<ProductClass, ProductMultiplier> multipliers = new HashMap<>();
  multipliers.put(CM12.getProductClass(), CM12);
  multipliers.put(IR10.getProductClass(), IR10);
  multipliers.put(EQ12.getProductClass(), EQ12);
  multipliers.put(CQ16.getProductClass(), CQ16);
  List<Sensitivity> s = Arrays.asList(CM1, CM2, CM3, CM4, CM5, CM6, CM7, CM8, CM9, CM10, CM11, CQ1, CQ2, CQ3, CQ4, CQ5, CQ6, CQ7, CQ8, CQ9, CQ10, CQ11, CQ12, CQ13, CQ14, CQ15, BC1, BC2, BC3, BC4, CNQ1, CNQ2, CNQ3, CNQ4, CNQ5, CNQ6, CNQ7, CNQ8, EQ1, EQ2, EQ3, EQ4, EQ5, EQ6, EQ7, EQ8, EQ9, EQ10, EQ11, IR1, IR2, IR3, IR4, IR5, IR6, IR7, IR8, IR9, FX1, FX2, FX3, FX4, CMV1, CMV2, CMV3, CMV4, CMV5, CMV6, CQV1, CQV2, CQV3, CQV4, CQV5, CNQV1, CNQV2, CNQV3, CNQV4, CNQV5, EQV1, EQV2, EQV3, EQV4, EQV5, EQV6, EQV7, EQV8, EQV9, EQV10, FXV1, FXV2, FXV3, FXV4, FXV5, IRV1, IRV2, IRV3, IRV4, IRV5, IRV6, IRV7);
  Assert.assertEquals(new BigDecimal("20991954959"), simm.calculateAdditional(s, multipliers, factors, notional, AN10).setScale(0, RoundingMode.HALF_UP));
}
 
开发者ID:AcadiaSoft,项目名称:simm-lib,代码行数:19,代码来源:AcadiaGlobalUnitTestV2_0.java

示例3: testWorstCase

import java.math.RoundingMode; //导入依赖的package包/类
public void testWorstCase() {
  int n = 2000000;
  int k = 200000;
  final long[] compareCalls = {0};
  Comparator<Integer> cmp =
      new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
          compareCalls[0]++;
          return o1.compareTo(o2);
        }
      };
  TopKSelector<Integer> top = TopKSelector.least(k, cmp);
  top.offer(1);
  for (int i = 1; i < n; i++) {
    top.offer(0);
  }
  assertThat(top.topK()).containsExactlyElementsIn(Collections.nCopies(k, 0));
  assertThat(compareCalls[0]).isAtMost(10L * n * IntMath.log2(k, RoundingMode.CEILING));
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:21,代码来源:TopKSelectorTest.java

示例4: TODO

import java.math.RoundingMode; //导入依赖的package包/类
@GwtIncompatible // TODO
@AndroidIncompatible // TODO(cpovirk): File BigDecimal.divide() rounding bug.
public void testDivNonZero() {
  for (long p : NONZERO_LONG_CANDIDATES) {
    for (long q : NONZERO_LONG_CANDIDATES) {
      for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
        long expected =
            new BigDecimal(valueOf(p)).divide(new BigDecimal(valueOf(q)), 0, mode).longValue();
        long actual = LongMath.divide(p, q, mode);
        if (expected != actual) {
          failFormat("expected divide(%s, %s, %s) = %s; got %s", p, q, mode, expected, actual);
        }
      }
    }
  }
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:17,代码来源:LongMathTest.java

示例5: calculate

import java.math.RoundingMode; //导入依赖的package包/类
private static double calculate(String data) {
    int[] counts = new int[26];
    Arrays.fill(counts, 0);

    int index, totalChars = 0;
    double numer = 0.0, denom;
    data = data.toLowerCase();

    for (Character c : data.toLowerCase().toCharArray()) {
        if (Character.isAlphabetic(c)) {
            index = c - 'a';
            ++counts[index];
            ++totalChars;
        }
    }

    for (Integer n : counts) {
        numer += (n * (n - 1));
    }

    denom = totalChars * (totalChars - 1);
    return BigDecimal.valueOf((numer / denom)).setScale(15, RoundingMode.HALF_UP).doubleValue();
}
 
开发者ID:FYP17-4G,项目名称:Aardvark,代码行数:24,代码来源:CalculateIC.java

示例6: listRewards

import java.math.RoundingMode; //导入依赖的package包/类
public void listRewards(Player player, VirtualCrate vc){
    if(!vc.showRewardsOnLeft) return;
    /* Home */
    StateContainer test = new StateContainer();
    Page.PageBuilder rewards = Page.builder();
    rewards.setAutoPaging(true);
    rewards.setTitle(TextSerializers.FORMATTING_CODE.deserialize(vc.displayName + " Rewards"));
    rewards.setEmptyStack(ItemStack.builder()
            .itemType(ItemTypes.STAINED_GLASS_PANE)
            .add(Keys.DYE_COLOR, DyeColors.BLACK)
            .add(Keys.DISPLAY_NAME, Text.of(TextColors.DARK_GRAY, "HuskyCrates")).build());
    for(Object[] e : vc.getItemSet()){
        CrateReward rew = (CrateReward)e[1];
        ItemStack item = rew.getDisplayItem().copy();
        if(vc.showProbability) {
            ArrayList<Text> lore = (ArrayList<Text>) item.getOrElse(Keys.ITEM_LORE, new ArrayList<>());
            lore.add(Text.of());

            lore.add(Text.of(TextColors.GRAY, TextStyles.ITALIC, "Win Probability: " + BigDecimal.valueOf((rew.getChance() / vc.getMaxProb()) * 100d).setScale(1, RoundingMode.HALF_UP).toString() + "%"));
            item.offer(Keys.ITEM_LORE, lore);
        }
        rewards.addElement(new Element(item));
    }
    test.setInitialState(rewards.build("rewards"));
    test.launchFor(player);
}
 
开发者ID:codeHusky,项目名称:HuskyCrates-Sponge,代码行数:27,代码来源:HuskyCrates.java

示例7: calculateIlpPacketDestinationAmountWithSlippage

import java.math.RoundingMode; //导入依赖的package包/类
/**
 * Given an ILP payment package final destination amount, reduce the value by a configured amount of allowable
 * slippage.
 *
 * Slippage occurs when the actual FX-rates between a quoted amount and an actual amount diverge due to various
 * factors outside of the control of the FX engine. For example, during quoting, the FX-rate may be 2:1, meaning 2
 * units of a source currency can be exchanged for 1 unit of a terminating currency. Thus, a sender sending 2 units
 * should expect 1 unit to arrive at the final destination. However, if by the time the payment is actually made, the
 * rates have "slipped" to 3:1, it is now more expensive for the sender to get 1 unit to the receiver. Thus, sending 2
 * units would only allow 2/3 of the terminating unit to arrive at the reciever, which means the amount of money the
 * receiver would receive has also "slipped." Because certain ledgers cannot guarantee quoted pricing, this connector
 * tolerates a certain amount of slippage as configured in {@link ConnectorConfig#getDefaultSlippagePercent()}.
 *
 * @param ilpPaymentDestinationAmount A {@link BigInteger} representing the amount, in units of the final-destination
 *                                    ledger, of the ILP payment.
 */
@VisibleForTesting
protected BigInteger calculateIlpPacketDestinationAmountWithSlippage(
    final BigInteger ilpPaymentDestinationAmount,
    final InterledgerAddress destinationLedgerPrefix
) {
  Objects.requireNonNull(ilpPaymentDestinationAmount);
  InterledgerAddress.requireAddressPrefix(destinationLedgerPrefix);

  // The amount can "slip" down by up-to {slippagePercent}
  final BigDecimal slippagePercent = this.connectorConfigurationService.getConnectorConfig()
      .getDefaultSlippagePercent();

  // Formula: amount * (1 - slippagePercent) => 500 * (1 - 1%) => 500 * (0.99) => 495
  final BigDecimal percentageInDecimal = BigDecimal.ONE.subtract(slippagePercent);

  return new BigDecimal(ilpPaymentDestinationAmount)
      // Uses infinite precision, which is simply signficant digits (not scale nor total number of digits).
      .multiply(percentageInDecimal).setScale(0, RoundingMode.HALF_UP)
      // Should never throw an exception because scale was set to 0 above.
      .toBigIntegerExact();
}
 
开发者ID:interledger,项目名称:java-ilp-connector,代码行数:38,代码来源:AbstractLedgerPluginEventHandler.java

示例8: MonetaryFormat

import java.math.RoundingMode; //导入依赖的package包/类
public MonetaryFormat() {
    // defaults
    this.negativeSign = '-';
    this.positiveSign = 0; // none
    this.zeroDigit = '0';
    this.decimalMark = '.';
    this.minDecimals = 2;
    this.decimalGroups = null;
    this.shift = 0;
    this.roundingMode = RoundingMode.HALF_UP;
    this.codes = new String[MAX_DECIMALS];
    this.codes[0] = CODE_BTC;
    this.codes[3] = CODE_MBTC;
    this.codes[6] = CODE_UBTC;
    this.codeSeparator = ' ';
    this.codePrefixed = true;
}
 
开发者ID:guodroid,项目名称:okwallet,代码行数:18,代码来源:MonetaryFormat.java

示例9: roundValue

import java.math.RoundingMode; //导入依赖的package包/类
/**
 * Rounds values by using a scale of 2 and rounding mode half up. If a non
 * rounded value equals zero (i.e. one of the factors is zero) convert it to
 * an empty string.
 * 
 * @param formatter
 * @param value
 * @param factors
 *            used in the price calculation
 * @return
 */
public static String roundValue(PriceConverter formatter, BigDecimal value,
        BigDecimal... factors) {

    if (BigDecimal.ZERO.compareTo(value) == 0) {
        if (factors.length == 0) {
            return EMPTY_STRING;
        } else if (containsZeroFactor(factors)) {
            return EMPTY_STRING;
        }
    }

    return formatter.getValueToDisplay(value.setScale(
            PriceConverter.NORMALIZED_PRICE_SCALING, RoundingMode.HALF_UP),
            true);
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:27,代码来源:ValueRounder.java

示例10: getTransaction

import java.math.RoundingMode; //导入依赖的package包/类
protected Optional<ITransaction> getTransaction(IInvntry invntry) {
  BigDecimal roq = orderManagementService.computeRecommendedOrderQuantity(invntry);
  if(BigUtil.greaterThanZero(roq)) {
    try {
      ITransaction t = JDOUtils.createInstance(ITransaction.class);
      t.setKioskId(invntry.getKioskId());
      t.setMaterialId(invntry.getMaterialId());
      t.setQuantity(roq.setScale(0, RoundingMode.CEILING));
      t.setType(ITransaction.TYPE_ORDER);
      t.setDomainId(invntry.getDomainId());
      t.setSourceUserId(Constants.SYSTEM_USER_ID);
      t.setTimestamp(new Date());
      t.setBatchId(null);
      t.setBatchExpiry(null);
      t.setReason("AUTOMATED");
      Optional<IKioskLink> vendor = chooseVendor(invntry.getKioskId(), invntry.getMaterialId());
      t.setLinkedKioskId(vendor.isPresent() ? vendor.get().getLinkedKioskId() : null);
      return Optional.of(t);
    } catch (ServiceException e) {
      LOGGER.warn("Error choosing vendor for inventory {0}:{1}", invntry.getKioskId(),
          invntry.getMaterialId(), e);
    }
  }
  return Optional.empty();
}
 
开发者ID:logistimo,项目名称:logistimo-web-service,代码行数:26,代码来源:OrderAutomationAction.java

示例11: initialize

import java.math.RoundingMode; //导入依赖的package包/类
public void initialize() 
{
   // 0-4 rounds down, 5-9 rounds up 
   currency.setRoundingMode(RoundingMode.HALF_UP);
   
   // listener for changes to tipPercentageSlider's value
   tipPercentageSlider.valueProperty().addListener(
      new ChangeListener<Number>() 
      {
         @Override
         public void changed(ObservableValue<? extends Number> ov, 
            Number oldValue, Number newValue) 
         {
            tipPercentage = 
               BigDecimal.valueOf(newValue.intValue() / 100.0);
            tipPercentageLabel.setText(percent.format(tipPercentage));
         }
      }
   );
}
 
开发者ID:cleitonferreira,项目名称:LivroJavaComoProgramar10Edicao,代码行数:21,代码来源:TipCalculatorController.java

示例12: calculateVATCosts

import java.math.RoundingMode; //导入依赖的package包/类
/**
 * Calculates the VAT details for the given VAT and cost data.
 * 
 * @param vatForCustomer
 *            The VAT details to be considered.
 * @return The VAT details containing the VAT amount and the total amount.
 */
public static VatRateDetails calculateVATCosts(VatRateDetails vatForCustomer) {
    BigDecimal totalCosts = vatForCustomer.getNetCosts();
    BigDecimal vatRate = vatForCustomer.getEffectiveVatRateForCustomer();
    if (vatRate != null) {
        BigDecimal fixSum = BigDecimal.ONE;
        BigDecimal percentBaseFactor = new BigDecimal(100);
        BigDecimal factor = fixSum.add(vatRate.divide(percentBaseFactor));
        BigDecimal total = totalCosts.multiply(factor).setScale(
                PriceConverter.NORMALIZED_PRICE_SCALING,
                RoundingMode.HALF_UP);
        totalCosts = total;
    }
    vatForCustomer.setTotalCosts(totalCosts);
    return vatForCustomer;
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:23,代码来源:CostCalculator.java

示例13: notional

import java.math.RoundingMode; //导入依赖的package包/类
@Test // tested: notional (netting with negative (absolute sum))
public void testAN3() {
  Map<String, AddOnNotionalFactor> factors = new HashMap<>();
  factors.put(AN1.getProduct(), AN1);
  Map<String, List<AddOnNotional>> notional = new HashMap<>();
  notional.put(AN3.getProduct(), Arrays.asList(AN3, AN4, AN5));
  Assert.assertEquals(new BigDecimal("2747250"), simm.calculateAdditional(EMPTY_LIST, EMPTY_MULT, factors, notional, ZERO_FIXED).setScale(0, RoundingMode.HALF_UP));
}
 
开发者ID:AcadiaSoft,项目名称:simm-lib,代码行数:9,代码来源:AcadiaAddOnUnitTestV2_0.java

示例14: testLog2NegativeAlwaysThrows

import java.math.RoundingMode; //导入依赖的package包/类
public void testLog2NegativeAlwaysThrows() {
  for (int x : NEGATIVE_INTEGER_CANDIDATES) {
    for (RoundingMode mode : ALL_ROUNDING_MODES) {
      try {
        IntMath.log2(x, mode);
        fail("Expected IllegalArgumentException");
      } catch (IllegalArgumentException expected) {}
    }
  }
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:11,代码来源:IntMathTest.java

示例15: getValue

import java.math.RoundingMode; //导入依赖的package包/类
/**
 * 判断data的类型,尝试解析成日期类型(返回{@link Date}),其次布尔类型(返回{@link Boolean}),
 * 然后数字类型(转变成字符串输出),
 * 前三种均解析失败则直接返回字符串data
 *
 * @param data
 * @return 解析后的值
 */
private Object getValue(String data) {
    Object value = null;
    try {
        //判断是否是日期类型
        Date date = DateUtils.parseDate(data, DATE_PATTERN);
        value = date;
    } catch (ParseException e) {
        //抛异常证明非日期类型
        if ("true".equalsIgnoreCase(data)) {
            value = Boolean.TRUE;
        } else if ("false".equalsIgnoreCase(data)) {
            value = Boolean.FALSE;
        } else {
            //判断是否数字
            try {
                double dbl = Double.parseDouble(data);
                if (this.scale == null || this.scale <= 0) {
                    //不四舍五入,直接输出
                    value = data;
                } else {
                    BigDecimal bd = new BigDecimal(dbl);
                    value = bd.toString().contains(".") ? bd.setScale(this.scale, RoundingMode.HALF_UP).toString() :
                            bd.toString();
                }
            } catch (NumberFormatException e1) {
                //证明不是数字,直接输出
                value = data;
            }
        }
    }

    return value;
}
 
开发者ID:FlyingHe,项目名称:UtilsMaven,代码行数:42,代码来源:XLSXReader.java


注:本文中的java.math.RoundingMode类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。