Gets a value object as Integer - Java java.lang

Java examples for java.lang:int

Description

Gets a value object as Integer

Demo Code


//package com.java2s;

public class Main {
    /**/*w  w w.  j a  va 2 s .  c o m*/
     * Gets a value object as Integer
     *
     * @param value Value to convert
     * @return Integer value or 0 if can not convert
     */
    public static Integer getValueAsInteger(Object value) {
        Integer valueAsInteger = 0;

        if (value instanceof String) {
            String sValue = (String) value;
            try {
                if (sValue.contains(".")) {
                    try {
                        Double tmpDouble = Double.parseDouble(sValue);
                        valueAsInteger = tmpDouble.intValue();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    if (!sValue.trim().isEmpty()) {
                        valueAsInteger = Integer.parseInt(sValue);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (value instanceof Integer) {
            valueAsInteger = (Integer) value;
        } else if (value instanceof Double) {
            Double doubleValue = (Double) value;
            try {
                valueAsInteger = doubleValue.intValue();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return valueAsInteger;
    }

    public static Integer getValueAsInteger(Double value) {
        return value.intValue();
    }
}

Related Tutorials