https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html
https://examples.javacodegeeks.com/core-java/apache/commons/lang3/math-lang3/numberutils/org-apache-commons-lang3-math-numberutils-example/
https://docs.oracle.com/javase/tutorial/java/data/beyondmath.html
https://stackoverflow.com/questions/18442503/java-isnan-how-it-works
Numbers Classes
Three reasons that you might use a
Number
object rather than a primitive:- As an argument of a method that expects an object (often used when manipulating collections of numbers).
- To use constants defined by the class, such as
MIN_VALUE
andMAX_VALUE
, that provide the upper and lower bounds of the data type. - To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).
Method | Description |
---|---|
byte byteValue() | Converts the value of this Number object to the primitive data type returned. |
int compareTo(Byte anotherByte) | Compares this Number object to the argument. |
boolean equals(Object obj) | Determines whether this number object is equal to the argument. The methods return true if the argument is not null and is an object of the same type and with the same numeric value.There are some extra requirements for Double and Float objects that are described in the Java API documentation. |
Each
Number
class contains other methods that are useful for converting numbers to and from strings and for converting between number systems. The following table lists these methods in the Integer
class. Methods for the other Number
subclasses are similar:Method | Description |
---|---|
static Integer decode(String s) | Decodes a string into an integer. Can accept string representations of decimal, octal, or hexadecimal numbers as input. |
static int parseInt(String s) | Returns an integer (decimal only). |
static int parseInt(String s, int radix) | Returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input. |
String toString() | Returns a String object representing the value of this Integer . |
static String toString(int i) | Returns a String object representing the specified integer. |
static Integer valueOf(int i) | Returns an Integer object holding the value of the specified primitive. |
static Integer valueOf(String s) | Returns an Integer object holding the value of the specified string representation. |
static Integer valueOf(String s, int radix) | Returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix. For example, if s = "333" and radix = 8, the method returns the base-ten integer equivalent of the octal number 333. |
Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for autoboxing and unboxing:
Primitive type | Wrapper class |
---|---|
boolean | Boolean |
byte | Byte |
char | Character |
float | Float |
int | Integer |
long | Long |
short | Short |
double | Double |
A Java NumberFormatException usually occurs when you try to do something like convert a String to a numeric value, like an int, float, double, long, etc.
// String str = "123456789"; this will throw NumberFormatException
String str = "123";
Integer i = Integer.parseInt(str); Byte b = Byte.parseByte(str); Double d = Double.parseDouble(str); Float f = Float.parseFloat(str); Long l = Long.parseLong(str); Short s = Short.parseShort(str); System.out.println("str = " + str); System.out.println("i = " + i); System.out.println("b = " + b); System.out.println("d = " + d); System.out.println("f = " + f); System.out.println("l = " + l); System.out.println("s = " + s);
We can use NumberUtils library to solve the issue:
Integer i = NumberUtils.createInteger(str);
Byte b = NumberUtils.toByte(str);
Double d = NumberUtils.createDouble(str);
Float f = NumberUtils.createFloat(str);
Long l = NumberUtils.createLong(str);
Short s = NumberUtils.toShort(str);
Formatting Numeric Print Output
The printf and format Methods
The
java.io
package includes a PrintStream
class that has two formatting methods that you can use to replace print
and println
. These methods, format
and printf
, are equivalent to one another. The familiar System.out
that you have been using happens to be a PrintStream
object, so you can invoke PrintStream
methods on System.out
. Thus, you can use format
or printf
anywhere in your code
where you have previously been using
print
or println
. For example,System.out.format(.....);
public PrintStream format(String format, Object... args)
where
format
is a string that specifies the formatting to be used and args
is a list of the variables to be printed using that formatting. A simple example would beSystem.out.format("The value of " + "the float variable is " + "%f, while the value of the " + "integer variable is %d, " + "and the string is %s", floatVar, intVar, stringVar);
Converter | Flag | Explanation |
---|---|---|
d | A decimal integer. | |
f | A float. | |
n | A new line character appropriate to the platform running the application. You should always use %n , rather than \n . | |
tB | A date & time conversion—locale-specific full name of month. | |
td, te | A date & time conversion—2-digit day of month. td has leading zeroes as needed, te does not. | |
ty, tY | A date & time conversion—ty = 2-digit year, tY = 4-digit year. | |
tl | A date & time conversion—hour in 12-hour clock. | |
tM | A date & time conversion—minutes in 2 digits, with leading zeroes as necessary. | |
tp | A date & time conversion—locale-specific am/pm (lower case). | |
tm | A date & time conversion—months in 2 digits, with leading zeroes as necessary. | |
tD | A date & time conversion—date as %tm%td%ty | |
08 | Eight characters in width, with leading zeroes as necessary. | |
+ | Includes sign, whether positive or negative. | |
, | Includes locale-specific grouping characters. | |
- | Left-justified.. | |
.3 | Three places after decimal point. | |
10.3 | Ten characters in width, right justified, with three places after decimal point. |
import java.util.Calendar; import java.util.Locale; public class TestFormat { public static void main(String[] args) { long n = 461012; System.out.format("%d%n", n); // --> "461012" System.out.format("%08d%n", n); // --> "00461012" System.out.format("%+8d%n", n); // --> " +461012" System.out.format("%,8d%n", n); // --> " 461,012" System.out.format("%+,8d%n%n", n); // --> "+461,012" double pi = Math.PI; System.out.format("%f%n", pi); // --> "3.141593" System.out.format("%.3f%n", pi); // --> "3.142" System.out.format("%10.3f%n", pi); // --> " 3.142" System.out.format("%-10.3f%n", pi); // --> "3.142" System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi); // --> "3,1416" Calendar c = Calendar.getInstance(); System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006" System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am" System.out.format("%tD%n", c); // --> "05/29/06" } }
The DecimalFormat Class
You can use the
java.text.DecimalFormat
class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. DecimalFormat
offers a great deal of flexibility in the formatting of numbers, but it can make your code more complex.Value | Pattern | Output | Explanation |
---|---|---|---|
123456.789 | ###,###.### | 123,456.789 | The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator. |
123456.789 | ###.## | 123456.79 | The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up. |
123.78 | 000000.000 | 000123.780 | The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#). |
12345.67 | $###,###.### | $12,345.67 | The first character in the pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in the formatted output . |
import java.text.*; public class DecimalFormatDemo { static public void customFormat(String pattern, double value ) { DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(value); System.out.println(value + " " + pattern + " " + output); } static public void main(String[] args) { customFormat("###,###.###", 123456.789); customFormat("###.##", 123456.789); customFormat("000000.000", 123.78); customFormat("$###,###.###", 12345.67); } }
The output is:
123456.789 ###,###.### 123,456.789 123456.789 ###.## 123456.79 123.78 000000.000 000123.780 12345.67 $###,###.### $12,345.67
Beyond Basic Arithmetic
The methods in the
Math
class are all static, so you call them directly from the class, like this:Math.cos(angle);
Constants and Basic Methods
Math.E
, which is the base of natural logarithms, andMath.PI
, which is the ratio of the circumference of a circle to its diameter.
Method | Description |
---|---|
double abs(double d) | Returns the absolute value of the argument. |
double ceil(double d) | Returns the smallest integer that is greater than or equal to the argument. Returned as a double. |
double floor(double d) | Returns the largest integer that is less than or equal to the argument. Returned as a double. |
double rint(double d) | Returns the integer that is closest in value to the argument. Returned as a double. |
long round(double d) | Returns the closest long or int, as indicated by the method's return type, to the argument. |
double min(double arg1, double arg2) | Returns the smaller of the two arguments. |
double max(double arg1, double arg2) | Returns the larger of the two arguments. |
Method | Description |
---|---|
double exp(double d) | Returns the base of the natural logarithms, e, to the power of the argument. |
double log(double d) | Returns the natural logarithm of the argument. |
double pow(double base, double exponent) | Returns the value of the first argument raised to the power of the second argument. |
double sqrt(double d) | Returns the square root of the argument. |
Method | Description |
---|---|
double sin(double d) | Returns the sine of the specified double value. |
double cos(double d) | Returns the cosine of the specified double value. |
double tan(double d) | Returns the tangent of the specified double value. |
double asin(double d) | Returns the arcsine of the specified double value. |
double acos(double d) | Returns the arccosine of the specified double value. |
double atan(double d) | Returns the arctangent of the specified double value. |
double atan2(double y, double x) | Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta . |
double toDegrees(double d) | Converts the argument to degrees or radians. |
Random Numbers
The
random()
method returns a pseudo-randomly selected number between 0.0 and 1.0. The range includes 0.0 but not 1.0. In other words: 0.0 <= Math.random() < 1.0
. To get a number in a different range, you can perform arithmetic on the value returned by the random method.
For example, to generate an integer between 0 and 9, you would write:
int number = (int)(Math.random() * 10);
By multiplying the value by 10, the range of possible values becomes
0.0 <= number < 10.0
.
Using
Math.random
works well when you need to generate a single random number. If you need to generate a series of random numbers, you should create an instance of java.util.Random
and invoke methods on that object to generate numbers.Summary of Numbers
- You use one of the wrapper classes –
Byte
,Double
,Float
,Integer
,Long
, orShort
– to wrap a number of primitive type in an object. The Java compiler automatically wraps (boxes) primitives for you when necessary and unboxes them, again when necessary. - The
Number
classes include constants and useful class methods. TheMIN_VALUE
andMAX_VALUE
constants contain the smallest and largest values that can be contained by an object of that type. ThebyteValue
,shortValue
, and similar methods convert one numeric type to another. ThevalueOf
method converts a string to a number, and thetoString
method converts a number to a string. - To format a string containing numbers for output, you can use the
printf()
orformat()
methods in thePrintStream
class. Alternatively, you can use theNumberFormat
class to customize numerical formats using patterns. - The
Math
class contains a variety of class methods for performing mathematical functions, including exponential, logarithmic, and trigonometric methods.Math
also includes basic arithmetic functions, such as absolute value and rounding, and a method,random()
, for generating random numbers.
The followings both will output true:
System.out.println(Float.isNaN(0.0f / 0.0f));
System.out.println(Double.isNaN(Math.sqrt(-1)));
Quiz
- Use the API documentation to find the answers to the following questions:
- Question: What
Integer
method can you use to convert anint
into a string that expresses the number in hexadecimal? For example, what method converts the integer 65 into the string "41"?
Answer:toHexString
- Question:What
Integer
method would you use to convert a string expressed in base 5 into the equivalentint
? For example, how would you convert the string "230" into the integer value 65? Show the code you would use to accomplish this task.
Answer:valueOf
. Here's how:
String base5String = "230"; int result = Integer.valueOf(base5String, 5);
- Question: What Double method can you use to detect whether a floating-point number has the special value Not a Number (
NaN
)?
Answer:isNaN
- Question: What
- Question: What is the value of the following expression, and why?
Integer.valueOf(1).equals(Long.valueOf(1))
Integer
and theLong
) have different types.
No comments:
Post a Comment