My header pretty much sums it up, in my application Im formatting a value only when the value is greater than 6 digits. When the value is thousands, e.g. 210,500, I want to display it as 210.5k, if the value is in the millions, e.g. 2,120,000, I want to display it as 2.12m. Currently the format string ('0,0.[00]a') will display both of these numbers to both decimal place(s), but I'd like that to be determined based on the whether or not the value is thousands or millions
Is the best way to figure this out to loop through the value until a decimal is reached and then determine the formatting based on that number? I have tried using the Custom Format object but am having a hard time understanding what's happening under the hood.
This value is displayed on a card and has to be formatted when there are 6 or more digits in the number. Formatting should be 1 decimal place for values in the thousands, and 2 decimal places shown for values in the millions (or greater)
Desired inputs and outputs:
210500 --> 210.5k
2120000 --> 2.12m
67500.89 --> 6.7k
6750000 --> 6.75m
16.75 --> 16.75
67530.85 --> 67.5k
675 --> 675
6700.05 --> 6700
2522.25 --> 2522
function formatValue(value: string | number, shorthandFormat: boolean = true, shorthandLength: number = 6) {
if (value === undefined || value === null) return '?';
let valueString = value.toString();
if (valueString.trim() === '') return '';
if (shorthandFormat) {
if (!shorthandLength || shorthandLength < 0) {
shorthandLength = 6;
}
if (valueString.length <= shorthandLength) {
shorthandFormat = false;
}
}
let numeralValue = numeral(value)
let formatter = shorthandFormat ? '0,0.[0]a' : '0,0.[00]';
let formattedValue = numeralValue.format(formatter);
return formattedValue;
}
Runnable snippet:
function formatValue(value, shorthandFormat = true, shorthandLength = 6) {
if (value === undefined || value === null) return '?';
let valueString = value.toString();
if (valueString.trim() === '') return '';
if (shorthandFormat) {
if (!shorthandLength || shorthandLength < 0) {
shorthandLength = 6;
}
if (valueString.length <= shorthandLength) {
shorthandFormat = false;
}
}
let numeralValue = numeral(value)
let formatter = shorthandFormat ? '0,0.[0]a' : '0,0.[00]';
let formattedValue = numeralValue.format(formatter);
return formattedValue;
}
// 210,500, I want to display it as 210.5k, if the value is in the millions, e.g. 2,120,000, I want to display it as 2.12m
console.log(formatValue(210500))
console.log(formatValue(2120000))
console.log(formatValue(675000))
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>