Utility class methods for converting Android String types to float double and int

  • 2021-09-16 07:58:13
  • OfStack

When doing the project, I encountered the need to convert the year (String) into int type, compare the years, extract them as methods by the way, and save them for later use.


public class ConvertUtil {
 
	// Put String Convert to float
	public static float convertToFloat(String number, float defaultValue) {
		if (TextUtils.isEmpty(number)) {
			return defaultValue;
		}
		try {
			return Float.parseFloat(number);
		} catch (Exception e) {
			return defaultValue;
		}
 
	}
 
	// Put String Convert to double
	public static double convertToDouble(String number, double defaultValue) {
		if (TextUtils.isEmpty(number)) {
			return defaultValue;
		}
		try {
			return Double.parseDouble(number);
		} catch (Exception e) {
			return defaultValue;
		}
 
	}
 
	// Put String Convert to int
	public static int convertToInt(String number, int defaultValue) {
		if (TextUtils.isEmpty(number)) {
			return defaultValue;
		}
		try {
			return Integer.parseInt(number);
		} catch (Exception e) {
			return defaultValue;
		}
	}
}

When you use it, you only need to call the above method (the second parameter is the default value):


int yeatInt = ConvertUtil.convertToInt("2017",2015);

Related articles: