How to go about formatting 1200 to 1.2k in java
Here is a solution that works for any long value and that I find quite readable (the core logic is done in the bottom three lines of the format
method).
It leverages TreeMap
to find the appropriate suffix. It is surprisingly more efficient than a previous solution I wrote that was using arrays and was more difficult to read.
private static final NavigableMap<Long, String> suffixes = new TreeMap<> ();
static {
suffixes.put(1_000L, "k");
suffixes.put(1_000_000L, "M");
suffixes.put(1_000_000_000L, "G");
suffixes.put(1_000_000_000_000L, "T");
suffixes.put(1_000_000_000_000_000L, "P");
suffixes.put(1_000_000_000_000_000_000L, "E");
}
public static String format(long value) {
//Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1);
if (value < 0) return "-" + format(-value);
if (value < 1000) return Long.toString(value); //deal with easy case
Entry<Long, String> e = suffixes.floorEntry(value);
Long divideBy = e.getKey();
String suffix = e.getValue();
long truncated = value / (divideBy / 10); //the number part of the output times 10
boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);
return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
}
Test code
public static void main(String args[]) {
long[] numbers = {0, 5, 999, 1_000, -5_821, 10_500, -101_800, 2_000_000, -7_800_000, 92_150_000, 123_200_000, 9_999_999, 999_999_999_999_999_999L, 1_230_000_000_000_000L, Long.MIN_VALUE, Long.MAX_VALUE};
String[] expected = {"0", "5", "999", "1k", "-5.8k", "10k", "-101k", "2M", "-7.8M", "92M", "123M", "9.9M", "999P", "1.2P", "-9.2E", "9.2E"};
for (int i = 0; i < numbers.length; i++) {
long n = numbers[i];
String formatted = format(n);
System.out.println(n + " => " + formatted);
if (!formatted.equals(expected[i])) throw new AssertionError("Expected: " + expected[i] + " but found: " + formatted);
}
}
How to go about formatting 1200 to 1.2k in Android studio
This should do the trick
String numberString = "";
if (Math.abs(number / 1000000) > 1) {
numberString = (number / 1000000).toString() + "m";
} else if (Math.abs(number / 1000) > 1) {
numberString = (number / 1000).toString() + "k";
} else {
numberString = number.toString();
}
Format a number as 2.5K if a thousand or more, otherwise 900
Sounds like this should work for you:
function kFormatter(num) { return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num)} console.log(kFormatter(1200)); // 1.2kconsole.log(kFormatter(-1200)); // -1.2kconsole.log(kFormatter(900)); // 900console.log(kFormatter(-900)); // -900
NumberFormat.format is also formatting digits as per locale
I found solution. We can get DecimalFormatSymbols instance and set Zerodigit character to avoid other digits symbol
DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat) numberFormat).getDecimalFormatSymbols();
decimalFormatSymbols.setZeroDigit('0');
Formatting numbers - grouping of decimal-place digits in Java
According to the API guide:
The grouping separator is commonly used for thousands, but in some
countries it separates ten-thousands. The grouping size is a constant
number of digits between the grouping characters, such as 3 for
100,000,000 or 4 for 1,0000,0000. If you supply a pattern with
multiple grouping characters, the interval between the last one and
the end of the integer is the one that is used. So "#,##,###,####" ==
"######,####" == "##,####,####".
This passage suggests that the grouping symbol can only be applied to the integer portion of the number. If we set a pattern like so:
String pattern = "###,###.###,###";
and pass it to an instance of DecimalFormat
, the result is:
java.lang.IllegalArgumentException: Malformed pattern "###,###.###,###"
whereas the more typical:
String pattern = "###,###.###";
works as expected.
setGroupingUsed
isn't applicable because it takes a boolean to indicate whether the number will be expressed with grouped digits. setGroupingSize
isn't applicable either, because it only governs how many digits comprise each group.
The only way to get what you want is to roll your own formatter.
Addendum:
Cracking open the source of DecimalFormat
reveals that the number to be formatted is divided into three sections: leftDigits
, or the leftmost digits of the integer portion of the number, zeroDigits
, or the rightmost digits of the integer portion of the number, and rightDigits
, or the fractional portion of the number.
The code includes the following (comment starts at line 2507):
// The position of the last grouping character is
// recorded (should be somewhere within the first two blocks
// of characters)
By "blocks," the comment clearly refers to leftDigits
and zeroDigits
, so even the developers assumed that grouping digits would only occur in the integer portion and made no provisions for grouping on the fractional portion (aside from throwing an exception).
Java: Format number in millions
String.format("%.2fM", theNumber/ 1000000.0);
For more information see the String.format javadocs.
How to display in TextView android K and M format if views or likes cross 1000 and more i.e.,1K or 1M using (JAVA)
you have to use if else statement
use this code -
String numberString = "";
if (Math.abs(number / 1000000) > 1) {
numberString = (number / 1000000).toString() + "m";
} else if (Math.abs(number / 1000) > 1) {
numberString = (number / 1000).toString() + "k";
} else {
numberString = number.toString();
}
How to convert number into K thousands M million and B billion suffix in jsp
Adapting the answer from over here it should look something like
public static String withSuffix(long count) {
if (count < 1000) return "" + count;
int exp = (int) (Math.log(count) / Math.log(1000));
return String.format("%.1f %c",
count / Math.pow(1000, exp),
"kMGTPE".charAt(exp-1));
}
Test code:
for (long num : new long[] { 0, 27, 999, 1000, 110592,
28991029248L, 9223372036854775807L })
System.out.printf("%20d: %8s%n", num, withSuffix(num));
Output:
0: 0
27: 27
999: 999
1000: 1.0 k
110592: 110.6 k
28991029248: 29.0 G
9223372036854775807: 9.2 E
Related Topics
Specifying Java Version in Maven - Differences Between Properties and Compiler Plugin
How to Bring a Window to the Front
Alert Handling in Selenium Webdriver (Selenium 2) with Java
Is There a Good Natural Language Processing Library
Connect 4 Check for a Win Algorithm
Determine Which Jar File a Class Is From
How to Calculate Elapsed Time from Now with Joda-Time
How to Perform String Diffs in Java
Java Type Inference: Reference Is Ambiguous in Java 8, But Not Java 7
Using Mockito with Multiple Calls to the Same Method with the Same Arguments
El Access a Map Value by Integer Key
Do JSON Keys Need to Be Unique
How to Go About Formatting 1200 to 1.2K in Java
Allowing Java to Use an Untrusted Certificate for Ssl/Https Connection