Java 17 Recipes


-3. Formatting Compact Number


Download 3.2 Mb.
Pdf ko'rish
bet68/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   64   65   66   67   68   69   70   71   ...   245
Bog'liq
Java 17 Recipes

4-3. Formatting Compact Number
 Problem
You want to represent a number in a short or human-readable form.
 Solution
Use the CompactNumberInstance method introduced in Java 12.
For example:
public static void main (String[] args) {
NumberFormat numberFormat = NumberFormat.
getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
String result = numberFormat.format(1000);
}
The following is the output.
1k
 How It Works
Java 12 introduced support for formatting a number in its compact form with the 
method. In the previous example, 1000 is formatted as “1K” in the en_US locale. The 
form depends on the style specified by NumberFormat.Style.
Chapter 4 Numbers aNd dates


113
4-4. Comparing int Values
 Problem
You need to compare two or more int values.
 Solution 1
Use the comparison operators to compare integer values against one another. In the 
following example, three int values are compared against each other, demonstrating 
various comparison operators.
public static void compareIntegers(){
int int1 = 1;
int int2 = 10;
int int3 = -5;
System.out.println(int1 == int2); // Result: false
System.out.println(int3 == int1); // Result: false
System.out.println(int1 == int1); // Result: true
System.out.println(int1 > int3); // Result: true
System.out.println(int2 < int3); // Result: false
}
The main class is:
public static void main(String[] args){
compareIntegers();
}
As you can see, comparison operators generate a boolean result.
 Solution 2
Use the Integer.compare(int,int) method to compare two int values numerically. The 
following lines could compare the same int values declared in the first solution.
System.out.println("Compare method -> int3 and int1:
" + Integer.compare(int3, int1));
// Result -1
Chapter 4 Numbers aNd dates


114
System.out.println("Compare method -> int2 and int1:
" + Integer.compare(int2, int1));
// Result 1
 How It Works
Perhaps the most used numeric comparisons are against two or more int values.
The Java language makes it easy to compare an int using the comparison operators
(see Table 
4-1
).

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   64   65   66   67   68   69   70   71   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling