Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions src/main/java/org/apache/datasketches/common/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -798,13 +798,21 @@ public static int bitAt(final long number, final int bitPos) {
/** Decimal Digits ***************************/

/**
* Computes the number of decimal digits of the number n
* @param n the given number
* @return the number of decimal digits of the number n
*/
public static int numDigits(long n) {
if ((n % 10) == 0) { n++; }
return (int) ceil(log(n) / log(10));
* Computes the minimum number of characters required to print the number n as a decimal.
* Negative numbers add one for the minus sign character.
* No other non-digit characters are assumed.
* @param n the given number, which may be negative.
* @return the number of characters required to print the number n as a decimal
*/
public static int numDigits(final long n) {
if (n == 0) { return 1; } //handles the zero special case
int count = (n < 0) ? 1 : 0; //handles the minus sign
long v = n;
while (v != 0) {
v /= 10;
count++;
}
return count;
}

/** Generic relational tests *****************/
Expand Down
23 changes: 23 additions & 0 deletions src/test/java/org/apache/datasketches/common/UtilTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import static org.apache.datasketches.common.Util.longToBytes;
import static org.apache.datasketches.common.Util.milliSecToString;
import static org.apache.datasketches.common.Util.nanoSecToString;
import static org.apache.datasketches.common.Util.numDigits;
import static org.apache.datasketches.common.Util.numberOfLeadingOnes;
import static org.apache.datasketches.common.Util.numberOfTrailingOnes;
import static org.apache.datasketches.common.Util.powerSeriesNextDouble;
Expand Down Expand Up @@ -241,6 +242,28 @@ public void checkCharacterPad() {
assertEquals(out,"zzzzzzzzzzzzPad 30, prepend z:");
}

@Test
public void checkNumDigits() {
for (long n = -1000; n <= 1000; n++) {
checkN(n);
}
final int maxExp = 18; //1E18 is the largest power of ten that fits in a signed long
long n = 1;
for (int exp = 0; exp <= maxExp; exp++) {
checkN(n);
checkN(n - 1);
checkN(-n);
checkN(-n + 1);
if (exp < maxExp) { n *= 10; } //the multiply past 1E18 would overflow
}
checkN(Long.MAX_VALUE);
checkN(Long.MIN_VALUE);
}

private static void checkN(final long n) {
assertEquals(numDigits(n), String.valueOf(n).length());
}

@Test
public void checkProbabilityFn1() {
checkProbability(.5, "Good");
Expand Down