Skip to content

Instantly share code, notes, and snippets.

@jprudent
Created September 29, 2011 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jprudent/1250054 to your computer and use it in GitHub Desktop.
Save jprudent/1250054 to your computer and use it in GitHub Desktop.
This method will transform a string to a number by removing non numbers characters (for memo)
public static String removeNonNumerics(String text) {
//remove everything except + - and digits
String num = text.replaceAll("[^-+\\.\\d]", "");
if (num.length() > 0) {
//remove + and - in middle of the string
num = num.charAt(0) + num.substring(1).replaceAll("[-+]", "");
//remove extra . (keep the first)
final int dot = num.indexOf(".");
if(dot > -1 && dot < num.length()){
//Note: in case dot == num.length() - 1, this returns ""
final String afterdot = num.substring(dot+1);
final String beforedot = num.substring(0, dot + 1);
num = beforedot + afterdot.replaceAll("\\.","");
}
}
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment