Skip to content
Merged
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
20 changes: 20 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,25 @@
assertEquals(out,"zzzzzzzzzzzzPad 30, prepend z:");
}

/**
* Check all the transition points where the number of decimal characters change.
*/
@Test
public void checkNumDigits() {
for (long n = 1; n > 0; n *= 10) { //n goes negative on rollover, which halts the loop
Comment thread
leerho marked this conversation as resolved.
Dismissed
checkN(n);
checkN(n - 1);
checkN(-n);
checkN(-n + 1);
}
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