Parse number string to integer. - Android java.lang

Android examples for java.lang:String Parse

Description

Parse number string to integer.

Demo Code


//package com.java2s;

import android.text.TextUtils;

public class Main {
    /**/*from   w  ww .j a v a  2s.c  o  m*/
     * 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