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

The following examples show how to use java.math.BigDecimal#intValue() . These examples are extracted from open source projects. 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 Project: SB_Elsinore_Server   File: OutputDevice.java    License: MIT License 6 votes vote down vote up
/**
 * Run through a cycle and turn the device on/off as appropriate based on the input duty.
 * @param duty The percentage of time / power to run.  This will only run if the duty
 *              is between 0 and 100 and not null.
 */
public void runCycle(BigDecimal duty) throws InterruptedException, InvalidGPIOException {
    // Run if the duty is not null and is between 0 and 100 inclusive.
    if (duty != null
            && duty.compareTo(BigDecimal.ZERO) > 0
            && duty.compareTo(HUNDRED) <= 0) {
        initializeSSR();

        duty = MathUtil.divide(duty, HUNDRED);
        BigDecimal onTime = duty.multiply(cycleTime);
        BigDecimal offTime = cycleTime.subtract(onTime);
        BrewServer.LOG.info("On: " + onTime
                + " Off; " + offTime);

        if (onTime.intValue() > 0) {
            setValue(true);
            Thread.sleep(onTime.intValue());
        }

        if (duty.abs().compareTo(HUNDRED) < 0 && offTime.intValue() > 0) {
            setValue(false);
            Thread.sleep(offTime.intValue());
        }
    }
}
 
Example 2
Source Project: jdmn   File: DefaultDurationType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Duration durationDivide(Duration first, BigDecimal second) {
    if (first == null || second == null) {
        return null;
    }

    try {
        if (isYearsAndMonths(first)) {
            long months = (first.getYears() * 12 + first.getMonths()) / second.intValue();
            return this.dataTypeFactory.newDurationYearMonth(String.format("P%dM", months));
        } else if (isDaysAndTime(first)) {
            long hours = 24L * first.getDays() + first.getHours();
            long minutes = 60L * hours + first.getMinutes();
            long seconds = 60L * minutes + first.getSeconds();
            seconds = seconds / second.intValue();
            return this.dataTypeFactory.newDurationDayTime(seconds * 1000L);
        } else {
            throw new DMNRuntimeException(String.format("Cannot divide '%s' by '%s'", first, second));
        }
    } catch (Exception e) {
        String message = String.format("durationDivide(%s, %s)", first, second);
        logError(message, e);
        return null;
    }
}
 
Example 3
private static Object coerceDecimalToExpectedType(BigDecimal value, Types.MinorType fieldType)
{
    switch (fieldType) {
        case INT:
        case TINYINT:
        case SMALLINT:
            return value.intValue();
        case BIGINT:
            return value.longValue();
        case FLOAT4:
            return value.floatValue();
        case FLOAT8:
            return value.doubleValue();
        default:
            return value;
    }
}
 
Example 4
public static Date getJavaDate( final BigDecimal date, final boolean excelBugCompatible, final int zeroDate ) {
  int correction = 1;

  final BigDecimal wholeDays = NumberUtil.performIntRounding( date );
  final int wholeDaysInt = wholeDays.intValue() - zeroDate;

  if ( excelBugCompatible ) {
    // if we deal with a date that is after the 28th februar, adjust the date by one to handle the fact
    // that excel thinks the 29th February 1900 exists.
    // by tuning this variable, we map the int-value for the 29th to the next day.
    if ( wholeDaysInt > 59 ) {
      correction = 0;
    }
  }

  final BigDecimal fractionNum = date.subtract( wholeDays );
  final BigDecimal fraction = fractionNum.multiply( DAY_MILLISECONDS );

  // the use of the calendar could be probably removed, as there is no magic in converting
  // a running number into a date.
  final GregorianCalendar calendar = new GregorianCalendar( 1900, 0, wholeDaysInt + correction );
  calendar.set( Calendar.MILLISECOND, fraction.setScale( 0, BigDecimal.ROUND_HALF_UP ).intValue() );
  return calendar.getTime();
}
 
Example 5
Source Project: Quicksql   File: SqlIntervalQualifier.java    License: MIT License 6 votes vote down vote up
private int[] fillIntervalValueArray(
    int sign,
    BigDecimal day,
    BigDecimal hour,
    BigDecimal minute,
    BigDecimal second,
    BigDecimal secondFrac) {
  int[] ret = new int[6];

  ret[0] = sign;
  ret[1] = day.intValue();
  ret[2] = hour.intValue();
  ret[3] = minute.intValue();
  ret[4] = second.intValue();
  ret[5] = secondFrac.intValue();

  return ret;
}
 
Example 6
/**
 * Returns the local rise/set time in the form HH:MM.
 * 
 * @param localTime
 *            <code>BigDecimal</code> representation of the local rise/set time.
 * @return <code>String</code> representation of the local rise/set time in HH:MM format.
 */
private String getLocalTimeAsString(BigDecimal localTimeParam) {
    if (localTimeParam == null) {
        return "99:99";
    }

    BigDecimal localTime = localTimeParam;
    if (localTime.compareTo(BigDecimal.ZERO) == -1) {
        localTime = localTime.add(BigDecimal.valueOf(24.0D));
    }
    String[] timeComponents = localTime.toPlainString().split("\\.");
    int hour = Integer.parseInt(timeComponents[0]);

    BigDecimal minutes = new BigDecimal("0." + timeComponents[1]);
    minutes = minutes.multiply(BigDecimal.valueOf(60)).setScale(0, RoundingMode.HALF_EVEN);
    if (minutes.intValue() == 60) {
        minutes = BigDecimal.ZERO;
        hour += 1;
    }
    if (hour == 24) {
        hour = 0;
    }

    String minuteString = minutes.intValue() < 10 ? "0" + minutes.toPlainString() : minutes.toPlainString();
    String hourString = (hour < 10) ? "0" + String.valueOf(hour) : String.valueOf(hour);
    return hourString + ":" + minuteString;
}
 
Example 7
Source Project: jdmn   File: DefaultSignavioDateLib.java    License: Apache License 2.0 5 votes vote down vote up
public XMLGregorianCalendar yearAdd(XMLGregorianCalendar dateTime, BigDecimal yearsToAdd) {
    XMLGregorianCalendar result = (XMLGregorianCalendar) dateTime.clone();
    int months = yearsToAdd.intValue();
    boolean isPositive = months > 0;
    Duration duration;
    duration = DATA_TYPE_FACTORY.newDurationYearMonth(
            isPositive, yearsToAdd.abs().intValue(), 0);
    result.add(duration);
    return result;
}
 
Example 8
/**
 * checks if a player can afford the trading fee depending on price
 *
 * @param player
 * @param price
 * @return true iff player has enough money
 */
public static boolean canPlayerAffordTradingFee(Player player, int price) {
	BigDecimal fee = calculateFee(player, price);
	List<Item> allEquipped = player.getAllEquipped("money");
	int ownedMoney = 0;
	for(Item item : allEquipped) {
		Money m = (Money) item;
		ownedMoney += m.getQuantity();
	}
	return fee.intValue() <= ownedMoney;
}
 
Example 9
@TLFunctionAnnotation("Narrowing conversion from decimal to integer value.")
public static final Integer decimal2integer(TLFunctionCallContext context, BigDecimal l) {
	if (l == null){
		return null;
	}
	if (l.compareTo(maxIntDecimal) > 0 || l.compareTo(minIntDecimal) <= 0) {
		throw new TransformLangExecutorRuntimeException("decimal2integer: " + l + " - out of range of integer");
	}
	return l.intValue();
}
 
Example 10
Source Project: lavaplayer   File: CombinedIpBlock.java    License: Apache License 2.0 5 votes vote down vote up
private void calculateHitProbabilities() {
  final BigDecimal size = new BigDecimal(this.size);
  final BigInteger sizeMultiplicator = BigInteger.valueOf(Integer.MAX_VALUE); // 100% target = Integer.MAX_VALUE
  for (int i = 0; i < ipBlocks.size(); i++) {
    final IpBlock ipBlock = ipBlocks.get(i);
    final BigInteger calcSize = ipBlock.getSize().multiply(sizeMultiplicator);
    final BigDecimal probability = new BigDecimal(calcSize).divide(size, BigDecimal.ROUND_HALF_UP);
    this.hitProbability[i] = probability.intValue();
  }
}
 
Example 11
Source Project: flash-waimai   File: ToolUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 把一个数转化为int
 *
 * @author fengshuonan
 * @Date 2017/11/15 下午11:10
 */
public static Integer toInt(Object val) {
    if (val instanceof Double) {
        BigDecimal bigDecimal = new BigDecimal((Double) val);
        return bigDecimal.intValue();
    } else {
        return Integer.valueOf(val.toString());
    }

}
 
Example 12
/**
 *
 * @param weight
 * @return a string representing the weight, based on the big decimal weight input
 */
public String getWeight(BigDecimal weight) {
  if (weight.compareTo(BigDecimal.ZERO) == 0) {
    return configuration.getZeroWeightString();
  }
  weight = weight.setScale(0, RoundingMode.UP);
  if (weight.intValue() == 1) {
    return "";
  }

  return String.format(configuration.getWeightingFormat(), weight.intValue());
}
 
Example 13
Source Project: cola-cloud   File: DecimalUtils.java    License: MIT License 5 votes vote down vote up
public static int toInt(Object value) {
 if (value instanceof Double) {
           BigDecimal bigDecimal = new BigDecimal((Double) value);
           return bigDecimal.intValue();
       } else {
           return Integer.valueOf(value.toString());
       }
}
 
Example 14
Source Project: erflute   File: DB2TableImportManager.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected Sequence importSequence(String schema, String sequenceName) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
        stmt = con.prepareStatement("SELECT * FROM SYSCAT.SEQUENCES WHERE SEQSCHEMA = ? AND SEQNAME = ?");
        stmt.setString(1, schema);
        stmt.setString(2, sequenceName);

        rs = stmt.executeQuery();

        if (rs.next()) {
            final Sequence sequence = new Sequence();

            sequence.setName(sequenceName);
            sequence.setSchema(schema);
            sequence.setIncrement(rs.getInt("INCREMENT"));
            sequence.setMinValue(rs.getLong("MINVALUE"));

            BigDecimal maxValue = rs.getBigDecimal("MAXVALUE");

            final int dataTypeId = rs.getInt("DATATYPEID");
            String dataType = null;
            if (dataTypeId == 16) {
                dataType = "DECIMAL(p)";
                sequence.setDecimalSize(rs.getInt("PRECISION"));
            } else if (dataTypeId == 24) {
                dataType = "INTEGER";
                if (maxValue.intValue() == Integer.MAX_VALUE) {
                    maxValue = null;
                }
            } else if (dataTypeId == 20) {
                dataType = "BIGINT";
                if (maxValue.longValue() == Long.MAX_VALUE) {
                    maxValue = null;
                }
            } else if (dataTypeId == 28) {
                dataType = "SMALLINT";
                if (maxValue.intValue() == Short.MAX_VALUE) {
                    maxValue = null;
                }
            } else {
                dataType = "";
            }

            sequence.setDataType(dataType);
            sequence.setMaxValue(maxValue);
            sequence.setStart(rs.getLong("START"));
            sequence.setCache(rs.getInt("CACHE"));

            boolean cycle = false;
            if ("Y".equals(rs.getString("CYCLE"))) {
                cycle = true;
            }

            sequence.setCycle(cycle);

            boolean order = false;
            if ("Y".equals(rs.getString("ORDER"))) {
                order = true;
            }

            sequence.setOrder(order);

            return sequence;
        }

        return null;
    } finally {
        close(rs);
        close(stmt);
    }
}
 
Example 15
@Override
public Enum87A toJava(BigDecimal dataValue) {
	return Enum87A.values()[dataValue.intValue()];
}
 
Example 16
Source Project: teaching   File: oConvertUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static int getInt(BigDecimal s, int defval) {
	if (s == null) {
		return (defval);
	}
	return s.intValue();
}
 
Example 17
@Override
public int extractHashCode(BigDecimal value) {
	return value.intValue();
}
 
Example 18
/**
 * Calculate the percentage of a given value in relation to other using a simple operation called 'Rule of 3'
 *
 * @param x the amount representing the value that we want to find (% of)
 * @param total representing 100%
 * @return the corresponding percentage of the total value
 */
public static int percentageOf(BigDecimal x, BigDecimal total) {

    requireNonNull(x);
    requireNonNull(total);

    x = x.setScale(2, RoundingMode.CEILING);

    final BigDecimal percentage = x.multiply(new BigDecimal(100)).divide(total, 2, RoundingMode.CEILING);

    return percentage.intValue();
}
 
Example 19
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
/** Convert from BigDecimal to Integer
 * @param bd The BigDecimal to convert
 * @return The resulting Integer
 * @throws Exception if anything goes wrong while doing the conversion.
 */
public static Integer bigDecimal2IntObject(BigDecimal bd)
    throws Exception {
    return (bd == null) ? new Integer(0) : new Integer(bd.intValue());
}