Parse number string to long. - Android java.lang

Android examples for java.lang:String Parse

Description

Parse number string to long.

Demo Code


//package com.java2s;

import android.text.TextUtils;

public class Main {
    /**// w  ww  .  ja  v  a  2  s.  co  m
     * Parse number string to long.
     * 
     * @param  num the long number string
     * @return     long number
     */
    public static long parseLong(String num) {
        if (TextUtils.isEmpty(num) || TextUtils.isEmpty(num.trim())) {
            return 0L;
        }

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

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

    /**
     * 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