Last active
April 13, 2017 17:07
-
-
Save ailabs-software/f51cc1ab02024c3901d5b75bc4af65c4 to your computer and use it in GitHub Desktop.
Is it okay to use StringBuilder like this?
This file contains hidden or 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 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