Example usage for java.lang Float intValue

List of usage examples for java.lang Float intValue

Introduction

In this page you can find the example usage for java.lang Float intValue.

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Float as an int after a narrowing primitive conversion.

Usage

From source file:com.github.jessemull.microflex.util.IntegerUtil.java

/**
 * Safely converts a number to an integer. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Number    number to parse/*from   ww w  . j  a v  a 2 s .co m*/
 * @return             parsed number
 * @throws   ArithmeticException    on overflow
 */
public static int toInteger(Number number) {

    /* Switch on class and convert to an int */

    String type = number.getClass().getSimpleName();
    int parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) number;
        parsed = by.intValue();
        break;

    case "Short":
        Short sh = (Short) number;
        parsed = sh.intValue();
        break;

    case "Integer":
        Integer in = (Integer) number;
        parsed = in.intValue();
        break;

    case "Long":
        Long lo = (Long) number;
        if (!OverFlowUtil.intOverflow(lo)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = lo.intValue();
        break;

    case "Float":
        Float fl = (Float) number;
        if (!OverFlowUtil.intOverflow(fl)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = fl.intValue();
        break;

    case "BigInteger":
        BigInteger bi = (BigInteger) number;
        if (!OverFlowUtil.intOverflow(bi)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = bi.intValue();
        break;

    case "BigDecimal":
        BigDecimal bd = (BigDecimal) number;
        if (!OverFlowUtil.intOverflow(bd)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = bd.intValue();
        break;

    case "Double":
        Double db = (Double) number;
        if (!OverFlowUtil.intOverflow(db)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = db.intValue();
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:es.eucm.eadandroid.homeapp.repository.resourceHandler.RepoResourceHandler.java

/**
 * Downloads any kind of file/*from w ww .j  ava2s  . co m*/
 */
public static void downloadFile(String url_from, String path_to, String fileName, ProgressNotifier pt) {

    try {

        HttpGet httpGet = new HttpGet(url_from);
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
        HttpConnectionParams.setSoTimeout(httpParameters, 42000);
        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        // Execute HTTP Get Request
        HttpResponse response = httpclient.execute(httpGet);

        pt.notifyProgress(0, "Connection established");

        File file = new File(path_to, fileName);

        FileOutputStream fos;

        try {
            fos = new FileOutputStream(file);

            InputStream in;
            try {

                float fileSize = response.getEntity().getContentLength();

                Log.d("fileSize", String.valueOf(fileSize));

                float iterNum = new Float(fileSize / (DOWNLOAD_BUFFER_SIZE) + 1).intValue();

                Log.d("numIter", String.valueOf(iterNum));

                float prIncrement = 100 / iterNum;

                Log.d("prIncrement", String.valueOf(prIncrement));

                Float progress = new Float(0);

                in = response.getEntity().getContent();
                byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
                int len1 = 0;
                while ((len1 = in.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);

                    progress += len1 / fileSize * 100;

                    pt.notifyProgress(progress.intValue(), "Downloading " + fileName);

                    Log.d("progress", String.valueOf(progress));

                }

                fos.close();
                in.close();

            } catch (IOException e) {

                pt.notifyError("Repository connection error");
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {

            pt.notifyError("Destination file error");
            e.printStackTrace();
        }

    } catch (Exception e1) {
        pt.notifyError("Repository connection error");
        e1.printStackTrace();
    }

}

From source file:iddb.core.util.Functions.java

public static String minutes2Str(Long minutes) {
    Float num;
    String suffix = "";
    if (minutes < 60) {
        num = new Float(minutes);
    } else if (minutes < 1440) {
        num = Float.valueOf(minutes) / 60;
        suffix = "h";
    } else if (minutes < 10080) {
        num = Float.valueOf(minutes) / 1440;
        suffix = "d";
    } else if (minutes < 525600) {
        num = Float.valueOf(minutes) / 10080;
        suffix = "w";
    } else {/*from   w w w .  j  a v  a  2 s  .c o  m*/
        num = Float.valueOf(minutes) / 525600;
        suffix = "y";
    }
    if ("0".equals(num.toString().substring(num.toString().indexOf(".") + 1))) {
        return String.format("%d%s", num.intValue(), suffix);
    }
    return String.format("%.2g%s", num, suffix); // 2=1 decimal
}

From source file:com.salesmanager.core.util.ProductUtil.java

public static String formatHTMLProductPrice(Locale locale, String currency, Product view,
        boolean showDiscountDate, boolean shortDiscountFormat) {

    if (currency == null) {
        log.error("Currency is null ...");
        return "-N/A-";
    }//from   ww  w .  ja  va  2  s. com

    int decimalPlace = 2;

    String prefix = "";
    String suffix = "";

    Map currenciesmap = RefCache.getCurrenciesListWithCodes();
    Currency c = (Currency) currenciesmap.get(currency);

    // regular price
    BigDecimal bdprodprice = view.getProductPrice();

    Date dt = new Date();

    // discount price
    java.util.Date spdate = null;
    java.util.Date spenddate = null;
    BigDecimal bddiscountprice = null;
    Special special = view.getSpecial();
    if (special != null) {
        spdate = special.getSpecialDateAvailable();
        spenddate = special.getExpiresDate();
        if (spdate.before(new Date(dt.getTime())) && spenddate.after(new Date(dt.getTime()))) {
            bddiscountprice = special.getSpecialNewProductPrice();
        }
    }

    // all other prices
    Set prices = view.getPrices();
    if (prices != null) {
        Iterator pit = prices.iterator();
        while (pit.hasNext()) {
            ProductPrice pprice = (ProductPrice) pit.next();
            if (pprice.isDefaultPrice()) {
                pprice.setLocale(locale);
                suffix = pprice.getPriceSuffix();
                bddiscountprice = null;
                spdate = null;
                spenddate = null;
                bdprodprice = pprice.getProductPriceAmount();
                ProductPriceSpecial ppspecial = pprice.getSpecial();
                if (ppspecial != null) {
                    if (ppspecial.getProductPriceSpecialStartDate() != null
                            && ppspecial.getProductPriceSpecialEndDate() != null) {
                        spdate = ppspecial.getProductPriceSpecialStartDate();
                        spenddate = ppspecial.getProductPriceSpecialEndDate();
                    }
                    bddiscountprice = ppspecial.getProductPriceSpecialAmount();
                }
                break;
            }
        }
    }

    double fprodprice = 0;
    ;
    if (bdprodprice != null) {
        fprodprice = bdprodprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // regular price String
    String regularprice = CurrencyUtil.displayFormatedCssAmountWithCurrency(bdprodprice, currency);

    // discount price String
    String discountprice = null;
    String savediscount = null;

    if (bddiscountprice != null && (spdate != null && spdate.before(new Date(dt.getTime()))
            && spenddate.after(new Date(dt.getTime())))) {

        double fdiscountprice = bddiscountprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();

        discountprice = CurrencyUtil.displayFormatedAmountWithCurrency(bddiscountprice, currency);

        double arith = fdiscountprice / fprodprice;
        double fsdiscount = 100 - arith * 100;

        Float percentagediscount = new Float(fsdiscount);

        savediscount = String.valueOf(percentagediscount.intValue());

    }

    StringBuffer p = new StringBuffer();
    p.append("<div class='product-price'>");
    if (discountprice == null) {
        p.append("<div class='product-price-price' style='width:50%;float:left;'>");
        p.append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</div>");
        p.append("<div class='product-line'>&nbsp;</div>");
    } else {
        p.append("<div style='width:50%;float:left;'>");
        p.append("<strike>").append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</strike>");
        p.append("</div>");
        p.append("<div style='width:50%;float:right;'>");
        p.append("<font color='red'>").append(discountprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</font>");
        if (!shortDiscountFormat) {
            p.append("<br>").append("<font color='red' style='font-size:75%;'>")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.save")).append(": ")
                    .append(savediscount)
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.percentsign")).append(" ")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.off")).append("</font>");
        }

        if (showDiscountDate && spenddate != null) {
            p.append("<br>").append(" <font style='font-size:65%;'>")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.until")).append("&nbsp;")
                    .append(DateUtil.formatDate(spenddate)).append("</font>");
        }

        p.append("</div>").toString();
    }
    p.append("</div>");
    return p.toString();

}

From source file:com.salesmanager.core.util.ProductUtil.java

/**
 * Format like <blue>[if discount striked]SYMBOL BASEAMOUNT</blue> [if
 * discount <red>SYMBOL DISCOUNTAMOUNT</red>] [if discount <red>Save:
 * PERCENTAGE AMOUNT</red>] [if qty discount <red>Buy QTY save [if price qty
 * discount AMOUNT] [if percent qty discount PERCENT]</red>]
 * //from  www .  j  av a2 s.com
 * @param ctx
 * @param view
 * @return
 */
public static String formatHTMLProductPriceWithAttributes(Locale locale, String currency, Product view,
        Collection attributes, boolean showDiscountDate) {

    if (currency == null) {
        log.error("Currency is null ...");
        return "-N/A-";
    }

    int decimalPlace = 2;

    String prefix = "";
    String suffix = "";

    Map currenciesmap = RefCache.getCurrenciesListWithCodes();
    Currency c = (Currency) currenciesmap.get(currency);

    // regular price
    BigDecimal bdprodprice = view.getProductPrice();

    // determine any properties prices
    BigDecimal attributesPrice = null;

    if (attributes != null) {
        Iterator i = attributes.iterator();
        while (i.hasNext()) {
            ProductAttribute attr = (ProductAttribute) i.next();
            if (!attr.isAttributeDisplayOnly() && attr.getOptionValuePrice().longValue() > 0) {
                if (attributesPrice == null) {
                    attributesPrice = new BigDecimal(0);
                }
                attributesPrice = attributesPrice.add(attr.getOptionValuePrice());
            }
        }
    }

    if (attributesPrice != null) {
        bdprodprice = bdprodprice.add(attributesPrice);// new price with
        // properties
    }

    // discount price
    java.util.Date spdate = null;
    java.util.Date spenddate = null;
    BigDecimal bddiscountprice = null;
    Special special = view.getSpecial();
    if (special != null) {
        bddiscountprice = special.getSpecialNewProductPrice();
        if (attributesPrice != null) {
            bddiscountprice = bddiscountprice.add(attributesPrice);// new
            // price
            // with
            // properties
        }
        spdate = special.getSpecialDateAvailable();
        spenddate = special.getExpiresDate();
    }

    // all other prices
    Set prices = view.getPrices();
    if (prices != null) {
        Iterator pit = prices.iterator();
        while (pit.hasNext()) {
            ProductPrice pprice = (ProductPrice) pit.next();
            if (pprice.isDefaultPrice()) {
                pprice.setLocale(locale);
                suffix = pprice.getPriceSuffix();
                bddiscountprice = null;
                spdate = null;
                spenddate = null;
                bdprodprice = pprice.getProductPriceAmount();
                if (attributesPrice != null) {
                    bdprodprice = bdprodprice.add(attributesPrice);// new
                    // price
                    // with
                    // properties
                }
                ProductPriceSpecial ppspecial = pprice.getSpecial();
                if (ppspecial != null) {
                    if (ppspecial.getProductPriceSpecialStartDate() != null
                            && ppspecial.getProductPriceSpecialEndDate() != null) {
                        spdate = ppspecial.getProductPriceSpecialStartDate();
                        spenddate = ppspecial.getProductPriceSpecialEndDate();
                    }
                    bddiscountprice = ppspecial.getProductPriceSpecialAmount();
                    if (bddiscountprice != null && attributesPrice != null) {
                        bddiscountprice = bddiscountprice.add(attributesPrice);// new price with
                        // properties
                    }
                }
                break;
            }
        }
    }

    double fprodprice = 0;
    ;
    if (bdprodprice != null) {
        fprodprice = bdprodprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // regular price String
    String regularprice = CurrencyUtil.displayFormatedCssAmountWithCurrency(bdprodprice, currency);

    Date dt = new Date();

    // discount price String
    String discountprice = null;
    String savediscount = null;
    if (bddiscountprice != null && (spdate != null && spdate.before(new Date(dt.getTime()))
            && spenddate.after(new Date(dt.getTime())))) {

        double fdiscountprice = bddiscountprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();

        discountprice = CurrencyUtil.displayFormatedAmountWithCurrency(bddiscountprice, currency);

        double arith = fdiscountprice / fprodprice;
        double fsdiscount = 100 - arith * 100;

        Float percentagediscount = new Float(fsdiscount);

        savediscount = String.valueOf(percentagediscount.intValue());

    }

    StringBuffer p = new StringBuffer();
    p.append("<div class='product-price'>");
    if (discountprice == null) {
        p.append("<div class='product-price-price' style='width:50%;float:left;'>");
        p.append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</div>");
        p.append("<div class='product-line'>&nbsp;</div>");
    } else {
        p.append("<div style='width:50%;float:left;'>");
        p.append("<strike>").append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</strike>");
        p.append("</div>");
        p.append("<div style='width:50%;float:right;'>");
        p.append("<font color='red'>").append(discountprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</font>").append("<br>").append("<font color='red' style='font-size:75%;'>")
                .append(LabelUtil.getInstance().getText(locale, "label.generic.save")).append(": ")
                .append(savediscount)
                .append(LabelUtil.getInstance().getText(locale, "label.generic.percentsign")).append(" ")
                .append(LabelUtil.getInstance().getText(locale, "label.generic.off")).append("</font>");

        if (showDiscountDate && spenddate != null) {
            p.append("<br>").append(" <font style='font-size:65%;'>")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.until")).append("&nbsp;")
                    .append(DateUtil.formatDate(spenddate)).append("</font>");
        }

        p.append("</div>").toString();
    }
    p.append("</div>");
    return p.toString();

}

From source file:org.rti.zcore.dar.transfer.access.IntegerConverter.java

@Override
public Object fromString(String str) {
    /* If empty tag. */

    if (str.compareTo("") == 0) {

        /* Default to zero. */

        str = "0";

    }/*from   w ww .j a va  2 s  . com*/

    Integer value = null;
    try {
        value = Integer.decode(str);
    } catch (NumberFormatException e) {
        try {
            Float floatValue = Float.valueOf(str);
            value = floatValue.intValue();
        } catch (NumberFormatException e1) {
            log.debug(e);
        }
    }
    return value;
}

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

public Integer evaluate(Float i) {
    if (i == null) {
        return null;
    } else {/* w ww. j a va2 s . co m*/
        return Integer.valueOf(i.intValue());
    }
}

From source file:gui.accessories.DownloadProgressWork.java

@Override
public Void doInBackground() throws FileNotFoundException {
    setProgress(0);//w w w .  jav a 2s .c om
    try {
        Thread.sleep(1000);
        downloadFile = new File(new File(portraitsFolder), portraitsFileName);
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    downloadFile = portraitsService.downloadPortraisFile(portraitsFileName, portraitsFolder);
                    filesCount = doUncompressZip(downloadFile);
                } catch (FileNotFoundException ex) {
                    LOG.error("Qu mal todo. " + ex.getMessage());
                } catch (ZipException ex) {
                    LOG.error("Qu mal todo descomprimiendo. " + ex.getMessage());
                }
            }
        });
        t.start();
        while (t.isAlive()) {
            Float progreso = downloadFile.length() / (float) fileSize;
            progreso *= 100;
            int progress = progreso.intValue();

            setProgress(progress);
        }

    } catch (InterruptedException ignore) {
    }
    return null;
}

From source file:woto.business.PaymentService.java

public JSONArray payAmount(JSONObject methodParam) throws ClassNotFoundException {

    JSONArray joArray = new JSONArray();

    DBConnection db = new DBConnection(true);
    try {//from   w w w. j  a va  2 s .c o  m

        int mem_id = Integer.parseInt("" + methodParam.get("mem_id"));
        int s_id = Integer.parseInt("" + methodParam.get("s_id"));
        long amount = Long.parseLong("" + methodParam.get("amount"));
        String pay_date = (String) methodParam.get("pay_date");
        int collector_id = Integer.parseInt("" + methodParam.get("collector_id"));
        int created_by = Integer.parseInt("" + getUserId());

        //Insert a new Bill for student    
        ParameterList paramList = new ParameterList();
        paramList.add("mem_id", "" + mem_id);
        paramList.add("s_id", "" + s_id);
        paramList.add("pay_date", pay_date);
        JSONArray paymentsFromDate = db.Execute("payment.logic", "getMemberPaymentFromDate",
                paramList.toJSONArray());
        if (paymentsFromDate.size() == 0) {
            joArray.addAll(payAmountAtEnd(db, methodParam));
        } else {

            //Get the list of amount pay after the min sche"select     gm_id,    substring(cast(t_date as char), 1, 10) p_date,    sum(amount) amount,    user_id from ( (select "+gmId+" gm_id,'"+ChittyUtil.ToDBDate(payDate)+"' t_date,"+amount+" amount,"+userId+" user_id,-999 trans_id) union (select gm_id,t_date,amount,user_id,p.trans_id from     payment p  inner join chitty.transaction  t ON t.trans_id = p.trans_id  where     gm_id = "+gmId+" ) ) dt group by gm_id , substring(cast(t_date as char), 1, 10) , user_id order by t_date "
            db.Execute("payment.logic", "deletePaymentFromDate", paramList.toJSONArray());

            joArray.addAll(payAmountAtEnd(db, methodParam));
            //Pay the amount payed till now.
            Iterator<JSONObject> iterator = paymentsFromDate.iterator();
            while (iterator.hasNext()) {
                JSONObject paymentFromDate = (JSONObject) iterator.next();

                Float f = Float.parseFloat("" + paymentFromDate.get("amount"));
                int ramount = f.intValue();

                JSONObject payment = new JSONObject();
                payment.put("mem_id", paymentFromDate.get("mem_id"));
                payment.put("s_id", paymentFromDate.get("s_id"));
                payment.put("pay_date", paymentFromDate.get("pay_date"));
                payment.put("amount", "" + ramount);
                payment.put("collector_id", paymentFromDate.get("collector_id"));
                payment.put("created_by", paymentFromDate.get("created_by"));
                joArray.addAll(payAmountAtEnd(db, payment));
            }

        }

        db.commit();
    } catch (Exception e) {
        db.rollback();
        throw e;
    }

    return joArray;
}

From source file:com.pureinfo.tgirls.servlet.TestServlet.java

private BufferedImage getImg(File _temp, float _i) throws IOException {
    BufferedImage output;/*from w  ww  . j a v  a2  s . co m*/
    Image img = ImageIO.read(_temp);
    int width = img.getWidth(null);
    int height = img.getHeight(null);

    Float f = width * _i;
    width = f.intValue();
    f = height * _i;
    height = f.intValue();

    output = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = output.getGraphics();
    g.drawImage(img, 0, 0, width, height, null);
    g.dispose();
    return output;
}