Parse number string to boolean. - Android java.lang

Android examples for java.lang:String Parse

Description

Parse number string to boolean.

Demo Code


//package com.java2s;

import android.text.TextUtils;

public class Main {
    /**/*ww  w  . j  a  v a  2 s  . c om*/
     * Parse number string to boolean.
     * 
     * @param  num the boolean number string
     * @return     boolean
     */
    public static boolean parseBoolean(String num) {
        if (TextUtils.isEmpty(num) || TextUtils.isEmpty(num.trim())) {
            return false;
        }

        boolean result = Boolean.parseBoolean(num);
        if (!result) {
            /* the num may be '0' or '1' */
            int value = parseInt(num);
            return value == 1 ? true : false;
        }

        return result;
    }

    /**
     * Parse number string to integer.
     * 
     * @param  num the integer number string
     * @return     int number
     */
    public static int parseInt(String num) {
        if (TextUtils.isEmpty(num) || TextUtils.isEmpty(num.trim())) {
            return 0;
        }

        try {
            return Integer.parseInt(num);
        } catch (NumberFormatException e) {
            /* if the num is float, get the integer */
            float value = parseFloat(num);

            return value == 0f ? 0 : Float.valueOf(value).intValue();
        }
    }

    /**
     * Parse number string to float.
     * 
     * @param  num the float number string
     * @return     float number
     */
    public static float parseFloat(String num) {
        if (TextUtils.isEmpty(num) || TextUtils.isEmpty(num.trim())) {
            return 0f;
        }

        try {
            return Float.parseFloat(num);
        } catch (NumberFormatException e) {
            return 0f;
        }
    }
}

Related Tutorials