Skip to content

Instantly share code, notes, and snippets.

@ailabs-software
Last active April 13, 2017 17:07
Show Gist options
  • Save ailabs-software/f51cc1ab02024c3901d5b75bc4af65c4 to your computer and use it in GitHub Desktop.
Save ailabs-software/f51cc1ab02024c3901d5b75bc4af65c4 to your computer and use it in GitHub Desktop.
Is it okay to use StringBuilder like this?
public class StringUtil
{
// Pad zeros.
// NOTE: Assumes base-10 representation of number.
public static String padNumber(double value, int len)
{
// Supports signed numbers.
boolean isNegative = value<0;
if (isNegative) {
value = Math.abs(value);
}
// At least this many.
int valueDigits = (int) Math.log10(value) + 1;
StringBuilder sb = new StringBuilder();
if (isNegative) {
sb.append('-');
}
sb.append( Double.toString(
// Pad zeros, at least as much as value.
value + Math.pow(10,
// Pad at least as much as length of value.
Math.max(len, valueDigits) )
).substring(1) );
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment