Last active
September 18, 2019 07:11
-
-
Save Mojtaba-Shafaei/ca6629c0c340940d17bfc4236d85256c to your computer and use it in GitHub Desktop.
A Java method that get a number as String and return comma-separated one.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String commaDelimited(String number) { | |
if (isBlank(number)) { | |
return ""; | |
} | |
number = number.replaceAll(",", ""); | |
if (number.length() <= 3) { | |
return number; | |
} | |
final char[] numberCharArray = number.toCharArray(); | |
final char[] sb = new char[numberCharArray.length + ((numberCharArray.length - 1) / 3)]; | |
int counter = 1; | |
int k = sb.length - 1; | |
for (int i = numberCharArray.length - 1; i >= 0; i--) { | |
sb[k] = numberCharArray[i]; | |
if (counter == 3 && k > 1) { | |
sb[--k] = ','; | |
counter = 1; | |
} else { | |
++counter; | |
} | |
--k; | |
} | |
return String.copyValueOf(sb); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment