## The Problem

Let’s say we want to write an algorithm for formatting very large and very small numbers using the standard SI decimal prefixes (because we really, really do!). We want something that will take numbers and create the abbreviated output, as below:

- 123784692876928714 → ‘123.78P’
- 1237846924 → ‘1.24G’
- 0.0000000000000002342 → ‘23.42f’
- 0.0000000002342 → ‘23.42n’
- 0.00000002342 → ‘234.22µ’
- 0.000012345 → ‘123.45m’
- 1234 → ‘1.23k’

I’m sure there are quite a few ways to do this. What if we could write something with only two non-repeated conditionals using a few math concepts in eight lines of code? Would you be more interested in learning about the math behind it? Let get started. First, let take a look at this algorithm and the lookup table it uses:

##### The Proposed Solution

```
// This is the list of standard SI unit prefixes
var symbols = {
'-8': 'y',
'-7': 'z',
'-6': 'a',
'-5': 'f',
'-4': 'p',
'-3': 'n',
'-2': 'µ',
'-1': 'm',
'0': '',
'1': 'k',
'2': 'M',
'3': 'G',
'4': 'T',
'5': 'P',
'6': 'E',
'7': 'Z',
'8': 'Y',
'9': 'H' // Though not official, 'hella' is hella big → 10^(9*3) or 10^27
};
function formatNumber(val, decimalPlaces) {
var exponent = Math.log(val) / Math.log(10);
var magnitudeExp = Math.floor(exponent);
var hasIntegerComponent = magnitudeExp >= 0;
var sign = (hasIntegerComponent) ? -1 : 1;
var adjustment = sign * (magnitudeExp % 3);
var significand = val / Math.pow(10, magnitudeExp + adjustment);
var index = (hasIntegerComponent) ? Math.floor(magnitudeExp / 3) : Math.ceil(magnitudeExp / 3);
return significand.toFixed(decimalPlaces) + symbols[''+index];
}
```

That’s it! That’s all there is to the algorithm! It will handle numbers having up to 29 digits and small numbers having a significant decimal place with 24 zeros in front of it. If that’s not good enough, an index and symbol for it should be added in the lookup table.

If math like this is foreign, a little head scratching might be in order. The math is actually pretty simple. There’s some interesting things about number bases and logarithms here.

## Number Bases

Number bases? As a programmer, one might be familiar with a few number bases — like decimal, hexadecimal, binary, and, perhaps, octal. A number base signifies how many symbols can be used to represent one digit. For instance, in decimal — or base 10 — there are 10 symbols that can represent a digit. These digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. In binary, two symbols are used — 0 and 1. In Hexadecimal, 16 symbols are used — 0-9 and A-F. In octal, the digits 0-7 are used — though, octal is rare these days.

Each digit in a number in a certain base has a certain value, which is related to the number base. Each number position, starting with the ones place in the 0^{th} position (the rightmost side) and continuing to the last or n^{th} position, has a value which is a multiple of the base. Here are examples in a few number bases.

##### Decimal

1,234,567

Position: | |||||||

Digit value: | |||||||

Place value: | |||||||

Position value: |

To get the value of the number in decimal, simply add the values up:

So each position has a value of the place times the value of the digit. In decimal, there is the ones place, the tens place, the hundreds place, the thousands place, the ten thousands place, and so on. Each digit happens to have the value that we normally give it, because the this is what we normally use and are used to.

What about other systems? Let us take a look.

##### Binary

##### 10101010

Position: | ||||||||

Digit value: | ||||||||

Place value: | ||||||||

Position value: |

To get the value of 10101010 in decimal, simply add the values up:

Again, the value of the position if the value of the digit times the place value. It only has two digits and they still have the same values as the decimal versions of those digits. What about a system with more symbols than ours?

##### Hexadecimal

DEAD

“Wait, what!? That doesn’t even look like a number!”

In hexadecimal, it’s a perfectly valid number. The digits A-F are used in addition to digits 0-9. In fact, the digit A comes right after 9 and it has a value of 10. The digits B-F have the values 11-15, respectively.

Position: | ||||

Digit value: | ||||

Place value: | ||||

Position value: |

To get the value of the number in decimal, simply add the values up:

##### Summary

Whew! What a whirlwind tour of number systems! This is all of the basic knowledge needed to understand what comes next. This covered the basics of number systems:

- Each number system in base uses digits.
- Each digit is in a position. Starting from the rightmost digit at and increasing with each digit moving leftward.
- Each digit in a number system has a value from to .
- Each position, , has a place value, or weight, which is .
- A digit with value, , in a position, , has a position value of
- Number has a value of the sum of the digit values times their weights.

This also means that every number is actually a polynomial in disguise:

The number of digits or places in a number indicates the order of the polynomial.

## Logarithms

What is a logarithm? A logarithm is a special mathematical function that gives us a special number. Normally, it is written or — the second means the base is (Euler’s constant). It is a special function that looks like this when graphed:

This graph conveys a few useful facts about the logarithm: The logarithm of a value is always less than the value. If an identity line of was drawn on the above graph of , the two graphs would actually never intersect. is only zero at . It could also be argued that doesn’t have a value at . The heart of a logarithm lies in the mathematics defining it.

The base logarithm gives the value of in the equation:

The logarithm in base of a number is written:

In the case of JavaScript’s Math.log(), it is a natural logarithm. It will solve for in this equation:

The base 10 logarithm, , can be found by taking . Generally, the base logarithm can be found by , where is a logarithm in any base available for you to use. Most likely it will be , since it is so useful in math.

Now why is a logarithm useful?

Logarithms are useful for numerous reasons:

- They can turn multiplication into addition. For instance, . Anyone can take the shortcut and mentally add up the numbers, but a computer can’t. However it can be programmed to use the properties a logarithms to change simplify parts of calculations without having to compute full values of repeated exponentiation until the final step. This also makes sure the numbers are smaller until the last step.
- If one wants to encode a certain number of states as digits in a system, one would like to know how many digits that many states would take up:
- In base 2, . We can use 1 bit to represent two states. We can use 3 bits to represent 8 states (000, 001, 010, 011, 100, 101, 110, 111), .
- In base 10, . This means we can use one decimal digit to represent 10 states — the range 0-9 encompasses ten digits. We can represent 1000 states with 3 digits (0-999), .
- Generally, where is the number of states to represent in base .

- In general, gives us the length of digits used to represent a number in the base number system. For example , which makes sense since we can represent 256 values from 0 through 255 with 8 bits. We cannot represent 256 with 8 bits, but we can with 9.
- In physics and information theory, a logarithm is related to a value called the entropy of the system.

The primary reason why a logarithm is useful in this case is because it yields an exponent that encodes a lot about a number. Here’s a an example with a number in decimal:

This could also be written as:

In this case, is the significand and is the magnitude.

Taking the base 10 log of 1,234 yields an interesting number. This number will be between 3 and 4. Why is it between 3 and 4? Well, and and this is somewhere between those two numbers. For instance, for any number n between 1,000,000,000 and 10,000,000,000 (not including 10,000,000,000), the will be between 9 and 10 (not including 10).

This is also a valid relationship:

Now why is it 3 and a fraction? Taking the integer part of gives three. Taking gives 1.234. This means . So taking this and turning it into a bunch of math gives us everything anyone would ever want to know about the number and the different logarithms. It also means this information can be used to derive the magnitude of the number and get it’s most significant digits for any number.

Here is every identity and step used to formally derive these quantities:

By definition, is an integer. The floor operation on the yields . Also by definition, must be less than one or greater or equal to zero. But why must it be greater than or equal to zero and less than one? A decimal significand is going to be between 1 and 9. If the significand was zero, the whole number would be zero. If the significand was less than 1, then the magnitude was wrong. If the significand is greater than 9, the magnitude was wrong. These numbers map to values of , where .

And of course, there’s the most straight forward way to get the significand:

This method, just using exponentiation and division, is probably more accurate than using the in most cases, since finding the exponent using the Math.log function is just an approximation. Using it to extrapolate the significant digits can lead to errors, especially with very large or small numbers.

## Back to the algorithm

The first few lines should be pretty obvious, given the explanation above:

```
var exponent = Math.log(val) / Math.log(10);
var magnitudeExp = Math.floor(exponent);
```

This figures out a few things:

```
var hasIntegerComponent = magnitudeExp >= 0;
var sign = (hasIntegerComponent) ? -1 : 1;
var adjustment = sign * (magnitudeExp % 3);
```

- If the number has just a fractional component (magnitudeExp is less than zero) or if it has a whole number part, too (magnitudeExp is greater than zero).
- The sign of the adjustment. If the number has a whole number part, the sign is negative and the adjustment is subtracted. If the the number is a fraction, the sign is positive and the adjustment is added.
- The adjustment itself. This is how many digits away from a grouping of 3 digits the number would be given the magnitudeExp.

If scientific notation was all that was required, the and would satisfy the problem. This algorithm is not actually converting to scientific notation. The algorithm should not show only one leading digit and a few decimal places. It should group digits into a maximum of three leading digits. Numbers between 000 – 999 will always be displayed before the suffix. It should be the equivalent of dividing the number by 1000, 1000000 and so forth (these numbers have counts of zeros which are multiples of three). This will group numbers into groups of 3 digits at most before the decimal place — this is where subtracting magnitudeExp % 3, (“magnitudeExp modulo 3”, the remainder of dividing by 3) comes from. That makes sure the abbreviations are only for place holders for the thousands, millions, billions, and so forth and never a placeholder for, say, ten thousand or a hundred million.

This code takes the adjustment into account when figuring out the significand to make sure that there is a group of at most 3 digits in the significand:

```
var significand = val / Math.pow(10, magnitudeExp + adjustment);
```

This code makes sure the suffix appended to the number matches up with the grouping of three most significant digits:

```
var index = (hasIntegerComponent) ? Math.floor(magnitudeExp / 3) : Math.ceil(magnitudeExp / 3);
return significand.toFixed(decimalPlaces) + symbols[''+index];
```

Depending on the logarithm of the number being positive or negative, we either take the floor or ceiling of magnitudeExp / 3, respectively. This makes sure we get the right integer for the index in the suffix lookup table.

That integer part of is actually the 1000, 1000000, 1000000000, and so forth in disguise. In fact Math.pow(10, Math.floor(magnitude / 3)) gives those values. This compresses the table of symbols so we don’t have something like the following, but rather the look-up table in the topmost code listing:

```
{
...
-1: 'm', -2: 'm', -3: 'm',
0: '', 1: '', 2: '',
3: 'k', 4: 'k', 5: 'k',
...
}
```

I suppose that the algorithm embodies a lot of knowledge about number systems, bases, and logarithms; but it’s very elegant. 😀 I haven’t tested how efficient it is compared to other methods, but, given the flexibility it has from the way it’s derived, it’s probably a decent trade-off.