Skip to content

Instantly share code, notes, and snippets.

@hugabor
Last active October 11, 2016 19:04
Show Gist options
  • Select an option

  • Save hugabor/5fbec4f5cfdab338a9b1fd3b120dfb85 to your computer and use it in GitHub Desktop.

Select an option

Save hugabor/5fbec4f5cfdab338a9b1fd3b120dfb85 to your computer and use it in GitHub Desktop.
Basic, often-used functions for stringifying positive numbers (in Java)
public final class NumStringUtil {
private NumStringUtil() {}
/**
* If the number string given has length less than the desired length, then
* the string is left-padded with zeroes and returned.
*
* @param numStr string to left-pad with zeroes
* @param length the desired length of the string
* @return the zero-padded string
*/
public static String fixLength(String numStr, int length) {
if (numStr == null) return null;
while (numStr.length() < length) {
numStr = "0" + numStr;
}
return numStr;
}
/**
* The input num with be converted to a string and left-padded with zeroes
* until it is the desired length.
*
* @param num the integer to return as a string of the specified length
* @param length the desired length of the string
* @return the zero-padded number as a string
*/
public static String fixLength(int num, int length) {
if (num < 0) return fixLength(0, length);
return fixLength("" + num, length);
}
/**
* The given double will be converted to a string that displays the
* specified number of decimal places.
*
* @param num the number to convert to a string
* @param decimalPlaces the number of decimal places desired
* @return the fixed number as a string
*/
public static String fix(double num, int decimalPlaces) {
String numStr = "" + (int) num;
if (decimalPlaces > 0) {
numStr += ".";
for (int i = 1; i <= decimalPlaces; ++i) {
numStr += String.valueOf(((int) (num * Math.pow(10, i))) % 10);
}
}
return numStr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment