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

The following examples show how to use java.math.BigDecimal#doubleValue() . 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: WonLostPercentageStrategy.java    From developerWorks with Apache License 2.0 6 votes vote down vote up
@Override
public String generateSql(String year, List<String[]> data) {
  //
  StringBuilder sb = new StringBuilder();
  LOG.debug("Generating SQL for stat cat => " + getStrategyName() + " and year => " + year);
  LOG.debug("There are " + data.size() + " lines of data to be processed...");
  for (String[] line : data) {
    int numWins = Integer.valueOf(line[2]);
    int numLosses = Integer.valueOf(line[3]);
    int numGames = numWins + numLosses;
    BigDecimal winLossPercentage = BigDecimal.valueOf((double)numWins/numGames).setScale(5,  RoundingMode.HALF_UP);
    String sql = "INSERT INTO " + /*SCHEMA_NAME + "." +*/ TABLE_NAME + "(" +
        "YEAR, TEAM_NAME, NUM_WINS, NUM_LOSSES, WIN_PERCENTAGE)"
        + "VALUES(" +
        Integer.valueOf(year) + "," +
        "'" + line[1] + "'," +
        numWins + "," +
        numLosses + "," +
        winLossPercentage.doubleValue() +
        ");" + "\n"
        ;
    sb.append(sql);
    incrementNumberOfRowsProcessed();
  }
  return sb.toString();
}
 
Example 2
Source File: StatsUtils.java    From developerWorks with Apache License 2.0 6 votes vote down vote up
public static BigDecimal normalize(BigDecimal value, BigDecimal minValue, BigDecimal maxValue) {
  BigDecimal ret;
  //
  // If the value is null, then set it to the min (nulls cause the program to crash)
  if (value == null) {
    value = minValue;
  }
  //
  ret = value.subtract(minValue).divide(maxValue.subtract(minValue), RoundingMode.HALF_UP);
  if (ret.doubleValue() >= 1.0) {
    ret = BigDecimal.valueOf(MAX_ALLOWABLE_VALUE);
  } else if (ret.doubleValue() <= 0.0) {
    ret = BigDecimal.valueOf(MIN_ALLOWABLE_VALUE);
  }
  //
  log.trace("Normalized value: " + ret + " = " + "(" + value + " - " + minValue + ") / (" + maxValue + " - " + minValue + ")");
  return ret;
}
 
Example 3
Source File: Probability.java    From minperf with Apache License 2.0 6 votes vote down vote up
public static double probabilitySplitIntoMSubsetsOfSizeN(int m, int n) {
    String key = "split-" + m + "/" + n;
    Double cached = PROBABILITY_CACHE.get(key);
    if (cached != null) {
        return cached;
    }
    BigInteger mm = BigInteger.valueOf(m);
    BigInteger mnf = factorial(n * m);
    BigInteger nf = factorial(n);
    BigInteger u = nf.pow(m).multiply(mm.pow(m * n));
    BigDecimal r = new BigDecimal(mnf).divide(
            new BigDecimal(u), 100, BigDecimal.ROUND_HALF_UP);
    double result = r.doubleValue();
    PROBABILITY_CACHE.put(key, result);
    return result;
}
 
Example 4
Source File: PayCommand.java    From EconomyLite with MIT License 6 votes vote down vote up
@Override
public void run(Player src, CommandContext args) {
    if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) {
        BigDecimal amount = BigDecimal.valueOf(args.<Double>getOne("amount").get());
        if (amount.doubleValue() <= 0) {
            src.sendMessage(messageStorage.getMessage("command.pay.invalid"));
        } else {
            User target = args.<User>getOne("player").get();
            if (!EconomyLite.getConfigManager().getValue(Boolean.class, false, "confirm-offline-payments") || target.isOnline()) {
                // Complete the payment
                pay(target, amount, src);
            } else {
                src.sendMessage(messageStorage.getMessage("command.pay.confirm", "player", target.getName()));
                // Check if they want to still pay
                src.sendMessage(TextUtils.yesOrNo(c -> {
                    pay(target, amount, src);
                }, c -> {
                    src.sendMessage(messageStorage.getMessage("command.pay.confirmno", "player", target.getName()));
                }));
            }

        }
    } else {
        src.sendMessage(messageStorage.getMessage("command.error"));
    }
}
 
Example 5
Source File: JRPercentageCalculatorFactory.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Object calculatePercentage(JRCalculable value, JRCalculable total)
{
	BigDecimal totalVal = (BigDecimal) total.getValue();
	BigDecimal val = (BigDecimal) value.getValue();
	BigDecimal percentage;
	if (totalVal != null && totalVal.doubleValue() != 0)
	{
		percentage = val.multiply(BigDecimal.valueOf(100L)).divide(totalVal, RoundingMode.HALF_UP);
	}
	else
	{
		percentage = BigDecimal.valueOf(0);
	}

	return percentage;
}
 
Example 6
Source File: MathUtils.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
public static double roundDouble(double value, int precision, RoundingMode roundingMode) {
    if (precision < 0)
        throw new IllegalArgumentException();

    try {
        BigDecimal bd = BigDecimal.valueOf(value);
        bd = bd.setScale(precision, roundingMode);
        return bd.doubleValue();
    } catch (Throwable t) {
        log.error(t.toString());
        return 0;
    }
}
 
Example 7
Source File: TransactionHistoryFragment.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}
 
Example 8
Source File: TransactionHistoryFragment.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}
 
Example 9
Source File: WeatherUndergroundJsonCurrent.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get the precipitation in the last hour in inches
 *
 * Used to update the channel current#precipitationHour
 *
 * @return the precipitation in the last hour in inches or null if not defined
 */
public BigDecimal getPrecipitationHourIn() {
    BigDecimal result = WeatherUndergroundJsonUtils.convertToBigDecimal(precip_1hr_in);
    if ((result != null) && (result.doubleValue() < 0.0)) {
        result = BigDecimal.ZERO;
    }
    return result;
}
 
Example 10
Source File: InfluxDBPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method returns an integer if possible if not a double is returned. This is an optimization
 * for influxdb because integers have less overhead.
 *
 * @param value the BigDecimal to be converted
 * @return A double if possible else a double is returned.
 */
private Object convertBigDecimalToNum(BigDecimal value) {
    Object convertedValue;
    if (value.scale() == 0) {
        logger.trace("found no fractional part");
        convertedValue = value.toBigInteger();
    } else {
        logger.trace("found fractional part");
        convertedValue = value.doubleValue();
    }
    return convertedValue;
}
 
Example 11
Source File: UserWalletFragment.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}
 
Example 12
Source File: TransactionHistoryFragment.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}
 
Example 13
Source File: StealsPerGame.java    From developerWorks with Apache License 2.0 5 votes vote down vote up
@Override
public String generateSql(String year, List<String[]> data) {
  StringBuilder sb = new StringBuilder();
  LOG.debug("Generating SQL for stat cat => " + getStrategyName() + " and year => " + year);
  LOG.debug("There are " + data.size() + " lines of data to be processed...");
  for (String[] line : data) {
    String teamName = line[1];
    int numGames = Integer.valueOf(line[2]);
    // Ignore W-L (don't care)
    int numSteals = Integer.valueOf(line[4]);
    // Compute SPG
    BigDecimal stealsPerGame = BigDecimal.valueOf((double) numSteals / numGames).setScale(5, RoundingMode.HALF_UP);
    String sql = "INSERT INTO " + /* SCHEMA_NAME + "." + */TABLE_NAME + "(" +
        "YEAR, TEAM_NAME, NUM_GAMES, NUM_STEALS, STEALS_PER_GAME"
        + ")"
        + "VALUES(" +
        Integer.valueOf(year) + "," +
        "'" + teamName + "'," +
        numGames + "," +
        numSteals + "," +
        stealsPerGame.doubleValue() +
        ");" + "\n";
    sb.append(sql);
    incrementNumberOfRowsProcessed();
  }
  return sb.toString();
}
 
Example 14
Source File: HistogramListener.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private Map getAssessmentStatisticsMap(List scoreList)
{
  // this function is used to calculate stats for an entire assessment
  // or for a non-autograded question
  // depending on data's instanceof 

  Iterator iter = scoreList.iterator();
  List<Double> doubles = new ArrayList<>();
  while (iter.hasNext())
  {
    Object data = iter.next();
    if (data instanceof AssessmentGradingData) {
  	  Double finalScore = ((AssessmentGradingData) data).getFinalScore();
  	  if (finalScore == null) {
  		  finalScore = Double.valueOf("0");
  	  }
      doubles.add(finalScore);
    }
    else
    {
      double autoScore = (double) 0.0;
      if (((ItemGradingData) data).getAutoScore() != null)
        autoScore = ((ItemGradingData) data).getAutoScore().doubleValue();
      double overrideScore = (double) 0.0;
      if (((ItemGradingData) data).getOverrideScore() != null)
        overrideScore =
          ((ItemGradingData) data).getOverrideScore().doubleValue();
      doubles.add(Double.valueOf(autoScore + overrideScore));
    }
  }

  if (doubles.isEmpty())
    doubles.add(new Double(0.0));

  doubles.sort(Comparator.naturalOrder());

  double[] scores = new double[doubles.size()];
  int i = 0;
  for (Double d : doubles) {
      BigDecimal bd = new BigDecimal(d);
      bd = bd.setScale(2, RoundingMode.HALF_UP);
      scores[i++] = bd.doubleValue();
  }

  Map statMap = new HashMap();

  double min = scores[0];
  double max = scores[scores.length - 1];
  double total = calTotal(scores);
  double mean = calMean(scores, total);
  int interval = 0;
  interval = calInterval(min, max); // SAM-2409
  int[] numStudents = calNumStudents(scores, min, max, interval);
 
  statMap.put("maxScore", castingNum(max,2));
  statMap.put("interval", Integer.valueOf(interval));
  statMap.put("numResponses", Integer.valueOf(scoreList.size()));
  // statMap.put("numResponses", Integer.valueOf(scores.length));

  statMap.put("totalScore",castingNum(total,2));
  statMap.put("mean", castingNum(mean,2));
  statMap.put("median", castingNum(calMedian(scores),2));
  statMap.put("mode", castingNumForMode(calMode(scores)));

  statMap.put("numStudentCollection", numStudents);
  statMap.put(
    "rangeCollection", calRange(numStudents, min, max, interval));
  statMap.put("standDev", castingNum(calStandDev(scores, mean),2));
  //NEW
  //statMap.put("columnHeight", calColumnHeight(numStudents));
  statMap.put("columnHeight", calColumnHeight(numStudents,scoreList.size()));

  statMap.put("arrayLength", Integer.valueOf(numStudents.length));
  statMap.put(
    "range",
    castingNum(scores[0],2) + " - " +
      castingNum(scores[scores.length - 1],2));
  statMap.put("q1", castingNum(calQuartiles(scores, 0.25),2));
  statMap.put("q2", castingNum(calQuartiles(scores, 0.5),2));
  statMap.put("q3", castingNum(calQuartiles(scores, 0.75),2));
  statMap.put("q4", castingNum(max,2));

  return statMap;
}
 
Example 15
Source File: BigDecimalUtils.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
 * 金额分割, 四舍五入金额
 * @param value       金额数值
 * @param scale       小数点后保留几位
 * @param mode        处理模式
 * @param splitNumber 拆分位数
 * @param splitSymbol 拆分符号
 * @return 指定格式处理的字符串
 */
public static String formatMoney(final BigDecimal value, final int scale, final int mode, final int splitNumber, final String splitSymbol) {
    if (value == null) return null;
    try {
        // 如果等于 0, 直接返回
        if (value.doubleValue() == 0) {
            return value.setScale(scale, mode).toPlainString();
        }
        // 获取原始值字符串 - 非科学计数法
        String valuePlain = value.toPlainString();
        // 判断是否负数
        boolean isNegative = valuePlain.startsWith("-");
        // 处理后的数据
        BigDecimal bigDecimal = new BigDecimal(isNegative ? valuePlain.substring(1) : valuePlain);
        // 范围处理
        valuePlain = bigDecimal.setScale(scale, mode).toPlainString();
        // 进行拆分小数点处理
        String[] values = valuePlain.split("\\.");
        // 判断是否存在小数点
        boolean isDecimal = (values.length == 2);

        // 拼接符号
        String symbol = (splitSymbol != null) ? splitSymbol : "";
        // 防止出现负数
        int number = Math.max(splitNumber, 0);
        // 格式化数据 - 拼接处理
        StringBuilder builder = new StringBuilder();
        // 进行处理小数点前的数值
        for (int len = values[0].length() - 1, i = len, splitPos = 1; i >= 0; i--) {
            // 获取数据
            char ch = values[0].charAt(i);
            builder.append(ch); // 保存数据
            // 判断是否需要追加符号
            if (number > 0 && splitPos % number == 0 && i != 0) {
                builder.append(symbol);
            }
            splitPos++;
        }
        // 倒序处理
        builder.reverse();
        // 存在小数点, 则进行拼接
        if (isDecimal) {
            builder.append(".").append(values[1]);
        }
        // 判断是否负数
        return isNegative ? "-" + builder.toString() : builder.toString();
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "formatMoney");
    }
    return null;
}
 
Example 16
Source File: ValueNumber.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@Override
public void setBigNumber( BigDecimal number ) {
  this.number = number.doubleValue();
}
 
Example 17
Source File: InfoCurricularCourse.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Double getTotalTrainingPeriodHours() {
    BigDecimal totalHours = getCurricularCourse().getTotalHoursByShiftType(ShiftType.TRAINING_PERIOD, null);
    return totalHours != null ? totalHours.doubleValue() : 0d;
}
 
Example 18
Source File: DataConversions.java    From Game with GNU General Public License v3.0 4 votes vote down vote up
public static double round(double value, int decimalPlace) {
	BigDecimal bd = new BigDecimal(value);
	bd = bd.setScale(decimalPlace, RoundingMode.HALF_UP);
	return (bd.doubleValue());
}
 
Example 19
Source File: NumberFormatWrapper.java    From super-csv-annotation with Apache License 2.0 3 votes vote down vote up
private Number convertWithBigDecimal(final Class<? extends Number> type, final BigDecimal number, final String str) {
    
    if(Byte.class.isAssignableFrom(type) || byte.class.isAssignableFrom(type)) {
        return lenient ? number.byteValue() : number.byteValueExact();
        
    } else if(Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type)) {
        return lenient ? number.shortValue() : number.shortValueExact();
        
    } else if(Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
        return lenient ? number.intValue() : number.intValueExact();
        
    } else if(Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) {
        return lenient ? number.longValue() : number.longValueExact();
        
    } else if(Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) {
        return number.floatValue();
        
    } else if(Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
        return number.doubleValue();
        
    } else if(type.isAssignableFrom(BigInteger.class)) {
        return lenient ? number.toBigInteger() : number.toBigIntegerExact();
        
    } else if(type.isAssignableFrom(BigDecimal.class)) {
        return number;
        
    }
    
    throw new IllegalArgumentException(String.format("not support class type : %s", type.getCanonicalName()));
    
}
 
Example 20
Source File: MathUtil.java    From Aria with Apache License 2.0 3 votes vote down vote up
/**
 * 设置精度
 * float/double的精度取值方式分为以下几种: <br>
 * java.math.BigDecimal.ROUND_UP <br>
 * java.math.BigDecimal.ROUND_DOWN <br>
 * java.math.BigDecimal.ROUND_CEILING <br>
 * java.math.BigDecimal.ROUND_FLOOR <br>
 * java.math.BigDecimal.ROUND_HALF_UP<br>
 * java.math.BigDecimal.ROUND_HALF_DOWN <br>
 * java.math.BigDecimal.ROUND_HALF_EVEN <br>
 *
 * @param scale 精度位数(保留的小数位数)
 * @param roundingMode 精度取值方式
 * @return 精度计算后的数据
 */
public static double round(double value, int scale, int roundingMode) {
  BigDecimal bd = new BigDecimal(value);
  bd = bd.setScale(scale, roundingMode);
  double d = bd.doubleValue();
  bd = null;
  return d;
}