Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

In this page you can find the example usage for java.math BigDecimal setScale.

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:org.apache.hadoop.hive.ql.udf.UDFTRUNC.java

public IntWritable evaluate(IntWritable val, IntWritable s) {
    if (val == null || s == null)
        return null;
    try {//from www  . java  2 s .  c  om
        IntWritable re = new IntWritable();
        int d = val.get();
        BigDecimal big = new BigDecimal(d);
        big = big.setScale(s.get(), 1);
        re.set((int) (big.doubleValue()));
        return re;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.apache.hadoop.hive.ql.udf.UDFTRUNC.java

public LongWritable evaluate(LongWritable val, IntWritable s) {
    if (val == null || s == null)
        return null;
    try {//from   w w w  . java2 s  . c  o  m
        LongWritable re = new LongWritable();
        long d = val.get();
        BigDecimal big = new BigDecimal(d);
        big = big.setScale(s.get(), 1);
        re.set((long) (big.doubleValue()));
        return re;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.apache.hadoop.hive.ql.udf.UDFTRUNC.java

public DoubleWritable evaluate(DoubleWritable val, IntWritable s) {
    if (val == null || s == null)
        return null;
    try {//from   www  .ja va 2 s.  c o m
        DoubleWritable re = new DoubleWritable();
        double d = val.get();
        String tmp = Double.toString(d);
        BigDecimal big = new BigDecimal(tmp);
        big = big.setScale(s.get(), 1);
        re.set(big.doubleValue());
        return re;
    } catch (Exception e) {
        return null;
    }
}

From source file:net.cloudkit.enterprises.infrastructure.freemarker.method.CurrencyMethod.java

@SuppressWarnings("rawtypes")
public Object exec(List arguments) {
    if ((arguments != null) && (!arguments.isEmpty()) && (arguments.get(0) != null)
            && (StringUtils.isNotEmpty(arguments.get(0).toString()))) {
        boolean bool1 = false;
        boolean bool2 = false;
        if (arguments.size() == 2) {
            if (arguments.get(1) != null) {
                bool1 = Boolean.valueOf(arguments.get(1).toString()).booleanValue();
            }/*from   w ww.  ja va  2s .co  m*/
        } else if (arguments.size() > 2) {
            if (arguments.get(1) != null) {
                bool1 = Boolean.valueOf(arguments.get(1).toString()).booleanValue();
            }
            if (arguments.get(2) != null) {
                bool2 = Boolean.valueOf(arguments.get(2).toString()).booleanValue();
            }
        }

        // BigDecimal.setScale()??
        // setScale(1)?????
        // setScale(1, BigDecimal.ROUND_DOWN)??2.35??2.3
        // setScale(1, BigDecimal.ROUND_UP)??2.35??2.4
        // setScale(1, BigDecimal.ROUND_HALF_UP)?2.35??2.4
        // setScale(1, BigDecimal.ROUND_HALF_DOWN)?2.35??2.35??
        BigDecimal localBigDecimal = new BigDecimal(arguments.get(0).toString());
        // newScale:PriceScale 2, roundingMode:PriceRoundType BigDecimal.ROUND_HALF_UP
        String str = localBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        // currencySign
        if (bool1) {
            str = "" + str;
        }
        // currencyUnit
        if (bool2) {
            str = str + "";
        }
        return new SimpleScalar(str);
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.homematic.internal.communicator.message.XmlRpcRequest.java

/**
 * Generates a value tag based on the type of the value.
 *//*from   www.j  a v a  2  s  . c  o m*/
private void generateValue(Object value) {
    if (value == null) {
        tag("string", "void");
    } else {
        Class<?> clazz = value.getClass();
        if (clazz == String.class || clazz == Character.class) {
            sb.append(StringEscapeUtils.escapeXml(value.toString()));
        } else if (clazz == Long.class || clazz == Integer.class || clazz == Short.class
                || clazz == Byte.class) {
            tag("int", value.toString());
        } else if (clazz == Double.class) {
            tag("double", String.valueOf(((Double) value).doubleValue()));
        } else if (clazz == Float.class) {
            BigDecimal bd = new BigDecimal((Float) value);
            generateValue(bd.setScale(6, RoundingMode.HALF_DOWN).doubleValue());
        } else if (clazz == BigDecimal.class) {
            generateValue(((BigDecimal) value).setScale(6, RoundingMode.HALF_DOWN).doubleValue());
        } else if (clazz == Boolean.class) {
            tag("boolean", ((Boolean) value).booleanValue() ? "1" : "0");
        } else if (clazz == Date.class) {
            tag("dateTime.iso8601", xmlRpcDateFormat.format(((Date) value)));
        } else if (value instanceof Calendar) {
            generateValue(((Calendar) value).getTime());
        } else if (value instanceof byte[]) {
            tag("base64", Base64.getEncoder().encodeToString((byte[]) value));
        } else if (clazz.isArray() || value instanceof List) {
            sb.append("<array><data>");

            Object[] array = null;
            if (value instanceof List) {
                array = ((List<?>) value).toArray();
            } else {
                array = (Object[]) value;
            }
            for (Object arrayObject : array) {
                sb.append("<value>");
                generateValue(arrayObject);
                sb.append("</value>");
            }

            sb.append("</data></array>");
        } else if (value instanceof Map) {
            sb.append("<struct>");

            for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
                sb.append("<member>");
                sb.append("<name>").append(entry.getKey()).append("</name>");
                sb.append("<value>");
                generateValue(entry.getValue());
                sb.append("</value>");
                sb.append("</member>");
            }

            sb.append("</struct>");
        } else {
            throw new RuntimeException("Unsupported XML-RPC Type: " + value.getClass());
        }
    }
}

From source file:com.servoy.extension.MarketPlaceExtensionProvider.java

private String getSizeString(int size) {
    String unit;/*from  www  . j  a v  a 2  s .c o m*/
    double value;
    if (size > 1024 * 1024) {
        unit = " MB"; //$NON-NLS-1$
        value = ((double) size) / 1024 / 1024;
    } else {
        unit = " KB"; //$NON-NLS-1$
        value = ((double) size) / 1024;
    }

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

    return bd.toPlainString() + unit;
}

From source file:org.jvnet.hudson.plugins.backup.utils.RestoreTask.java

public void run() {
    assert (logFilePath != null);
    assert (backupFileName != null);

    startDate = new Date();
    try {//from  w w w  .  ja  v  a2s  . c om
        logger = new BackupLogger(logFilePath, configuration.isVerbose());
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unable to open log file for writing : {0}", logFilePath);
        return;
    }

    logger.info("Restore started at " + getTimestamp(startDate));

    File directory = new File(hudsonWorkDir);

    String tempDirectoryPath = hudsonWorkDir + "_restore";
    logger.info("Working into " + tempDirectoryPath + " directory");

    File temporary_directory = new File(tempDirectoryPath);

    if (temporary_directory.exists()) {
        logger.info("A old restore working dir exists, cleaning ...");
        try {
            FileUtils.deleteDirectory(temporary_directory);
        } catch (IOException e) {
            logger.error("Unable to delete " + tempDirectoryPath);
            e.printStackTrace(logger.getWriter());
            finished = true;
            return;
        }
    }
    temporary_directory.mkdir();

    File archive = new File(backupFileName);

    logger.info("Uncompressing archive file...");
    UnArchiver unAchiver = configuration.getArchiveType().getUnArchiver();

    try {
        unAchiver.unArchive(archive, tempDirectoryPath);
    } catch (Exception e) {
        e.printStackTrace(logger.getWriter());
        logger.error("Error uncompressiong archive : " + e.getMessage());
        finished = true;
        return;
    }

    // Not using tools like FileUtils.deleteDirectory
    // because it is failing with non existing symbolic links
    logger.info("Removing old configuration files...");
    delete(directory);

    logger.info("Making temporary directory the hudson home...");
    temporary_directory.renameTo(directory);

    logger.info("*****************************************");
    logger.info("Reloading hudson configuration from disk.");
    logger.info("*****************************************");

    StaplerRequest request = FakeObject.getStaplerRequestFake(servletContext);
    StaplerResponse response = FakeObject.getStaplerResponseFake();

    try {
        Hudson.getInstance().doReload(request, response);
    } catch (IOException e) {
        logger.error("Error reloading config files from disk.");
        logger.error("Call this method manually");
        e.printStackTrace(logger.getWriter());
    }

    endDate = new Date();
    logger.info("Backup end at " + getTimestamp(endDate));
    BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime());
    delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP);
    delay = delay.divide(new BigDecimal("1000"));

    logger.info("[" + delay.toPlainString() + "s]");
    finished = true;
    logger.close();
}

From source file:org.kalypso.model.wspm.tuhh.schema.simulation.MultipleRunoffReader.java

public void readKM() {
    try {//from w  ww. j a va 2  s  .  co m
        final FileFilter kmFilter = FileFilterUtils.suffixFileFilter(".km", IOCase.INSENSITIVE); //$NON-NLS-1$
        final File[] kmFiles = m_kmDir.listFiles(kmFilter);

        // REMARK: the way we read km/polynomial files it's bit tricky to get the slope
        // However this is not a problem, as we are calculating we a uniform steady slope,
        // which is defined in the calculation
        final BigDecimal startSlope = m_calculation.getStartSlope();
        final BigDecimal slope = startSlope.setScale(5, RoundingMode.HALF_UP);

        final KMFileReader reader = new KMFileReader(kmFiles, m_log, m_intervalIndex, slope);
        reader.read();
    } catch (final Throwable e) {
        m_log.log(e, Messages.getString("org.kalypso.model.wspm.tuhh.schema.simulation.KMProcessor.0"), //$NON-NLS-1$
                e.getLocalizedMessage());
    }
}

From source file:org.lockss.util.NumberUtil.java

/**
 * Round to given number of digits after decimal point
 * /* ww  w.ja  v a2s  .c o m*/
 * @param d
 * @param decimalPlace
 * @return argument rounded to 
 */
public static double roundToNDecimals(double d, int decimalPlaces) {
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN);
    return bd.doubleValue();
}

From source file:org.cirdles.ambapo.LatLongToUTM.java

/**
 * Converts BigDecimal latitude longitude to UTM 
 * /*from w w w.ja va2 s  .  c om*/
 * @param latitude
 * @param longitude
 * @param datumName
 * @return UTM
 * @throws java.lang.Exception
 * 
 * 
 */
public static UTM convert(BigDecimal latitude, BigDecimal longitude, String datumName) throws Exception {

    Datum datum = Datum.valueOf(datumName);

    BigDecimal meridianRadius = new BigDecimal(datum.getMeridianRadius());
    BigDecimal eccentricity = new BigDecimal(datum.getEccentricity());

    BigDecimal latitudeRadians = latitude.abs().multiply(new BigDecimal(Math.PI)).divide(new BigDecimal(180.0),
            PRECISION, RoundingMode.HALF_UP);

    int zoneNumber = calcZoneNumber(longitude);

    BigDecimal zoneCentralMeridian = calcZoneCentralMeridian(zoneNumber);

    BigDecimal changeInLongitudeDegree = (longitude.subtract(zoneCentralMeridian)).abs().setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal changeInLongitudeRadians = (changeInLongitudeDegree.multiply(new BigDecimal(Math.PI)))
            .divide(new BigDecimal(180), PRECISION, RoundingMode.HALF_UP);

    BigDecimal conformalLatitude = calcConformalLatitude(eccentricity, latitudeRadians).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal tauPrime = (new BigDecimal(Math.tan(conformalLatitude.doubleValue()))).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal xiPrimeNorth = calcXiPrimeNorth(changeInLongitudeRadians, tauPrime).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal etaPrimeEast = calcEtaPrimeEast(changeInLongitudeRadians, tauPrime).setScale(PRECISION,
            RoundingMode.HALF_UP);

    double[] alphaSeries = datum.getAlphaSeries();

    BigDecimal xiNorth = calcXiNorth(xiPrimeNorth, etaPrimeEast, alphaSeries).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal etaEast = calcEtaEast(xiPrimeNorth, etaPrimeEast, alphaSeries).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal easting = calcEasting(meridianRadius, etaEast, longitude, zoneCentralMeridian)
            .setScale(PRECISION, RoundingMode.HALF_UP);
    BigDecimal northing = calcNorthing(meridianRadius, xiNorth, latitude).setScale(PRECISION,
            RoundingMode.HALF_UP);

    char zoneLetter = calcZoneLetter(latitude);
    char hemisphere = calcHemisphere(latitude);

    if (easting.doubleValue() > UTM.MAX_EASTING)
        easting = new BigDecimal(UTM.MAX_EASTING);
    if (easting.doubleValue() < UTM.MIN_EASTING)
        easting = new BigDecimal(UTM.MIN_EASTING);

    if (northing.doubleValue() > UTM.MAX_NORTHING)
        northing = new BigDecimal(UTM.MAX_NORTHING);
    if (northing.doubleValue() < UTM.MIN_NORTHING)
        northing = new BigDecimal(UTM.MIN_NORTHING);

    UTM utm = new UTM(easting.setScale(SCALE, RoundingMode.HALF_UP),
            northing.setScale(SCALE, RoundingMode.HALF_UP), hemisphere, zoneNumber, zoneLetter);

    return utm;
}