天天看点

java 数据Number、Math基本算数运算之外 java除了支持各种基本的算术运算(+, -, *, /, 和 %)之外,也为各种复杂的数学运算提供了工具类Math。通过Math类可以完成指数、对数、反三角函数等复杂的运算。 由于Math类的方法都是静态的,你可以在类里直接调用Math类的方法,如下:  Math.cos(angle);

一个初出茅庐的小子与大家共享一些关于Number和Math的使用,因水平有限,难免有写的不完善的地方,嘻嘻。看完之后,希望可以留下你珍贵的指导意见。

The Numbers Classes

在写代码的时候,也许会使用到java 各种的基本数据类型,如下:

int i = 500;

float gpa = 3.65f;

byte mask = 0xff;

然而,在面向对象开发的过程,我们更倡导你使用对象来代替各种的基本数据类型,而java也为各种基本数据类型提供了wrapper class(包装类)——这些wrapper class封装了对应的基本数据。通常,编译器会为我们完成这种封装——换句话说就是,如果一个方法需要Object类型的参数,而实际提供的值确实2、3等数值,这时编译器会把2、3等数值封装成对应的wrapper class;类似,如果一个方法需要基本数据类型的参数,而实际提供的却似Object类型,这时编译器会Object类型的参数拆成几本数据类型——而这就所为的“自动拆装箱原理”。

接着给出一个自动拆装箱的demo:

1

2

3

4

<code>Integer x, y;</code>

<code>x = </code><code>12</code><code>;</code>

<code>y = </code><code>15</code><code>;</code>

<code>System.out.println(x+y);</code>

<a target="_blank" href="http://blog.51cto.com/attachment/201308/193447827.png"></a>

Methods  Implemented by all Subclasses of Number

方法

描述

byte byteValue()

short shortValue()

int intValue()

long longValue()

 float floatValue()

 double doubleValue()

将Number对象转换成对应的基本数据类型

int compareTo(Byte anotherByte)

 int compareTo(Double anotherDouble)

 int compareTo(Float anotherFloat)

 int compareTo(Integer anotherInteger)

 int compareTo(Long anotherLong)

 int compareTo(Short anotherShort)

将Number对象的值与参数anotherXxx的值进行比较

boolean equals(Object obj)

判断Number对象和参数Object是否相同。

当两个对象不为空且数据类型和值都一致的情况下,才返回true。

如果判断的是Double和Float类型,则还需要一些额外的参数,详情可参考java API的官方文档。

对于与String类型的数据与及各种进制数据之间的装换,每个Number类(在这指其子类)都有着相对应的方法。下表列出了Integer对象与String数据和进制之间相互转换的方法。其他的Number类都与之类似。

Integer类的转换方法

static Integer decode(String s)

将String解码为Integer。String数据可以是十进制、八进制或者十六进制。

static int parseInt(String s)

返回一个int值,String只能是十进制的数据。

static int parseInt(String s, int radix)

将指定进制的String数据转换成int值。参数radix指多少进制(可以是2、8、10或者16)

String toString()

将Integer数据转成String类型

static String toString(int i)

返回一个指定整数的String对象

static Integer valueOf(int i)

返回一个表示指定的int值的Integer实例。

static Integer valueOf(String s)

返回String数据的Integer对象

static Integer valueOf(String s, int radix)

将指定进制的String数据转换为Integer类型。如当s=”333”,radix=8时,会返回数据为219的Integer实例。

一直以来,也许你都是在使用标准输出(System.out)输出各种数据,之所以可以这样做,是因为所有Number数据都可以转换成String类型。然而,有时候你可能需要更好地控制数据的输出,则需要使用java提供的其他方法。

其方法原型如下:

<code>System.out.format(</code><code>"The value of "</code><code>+ </code><code>"the float variable is "</code> <code>+ </code><code>"%f, while the value of the "</code>

<code>                           </code><code>+ </code><code>"integer variable is %d, "</code> <code>+ </code><code>"and the string is %s"</code><code>, floatVar, intVar, stringVar);</code>

<code>int</code> <code>i = </code><code>461012</code><code>;</code>

<code>System.out.format(</code><code>"The value of i is: %d%n"</code><code>, i);</code>

“%d”代表了十进制数据(在这里值i),“%n”代表了输出换行,所以其输出如下:

5

<code>float</code> <code>floatVar = </code><code>123</code><code>.37f;</code>

<code>int</code> <code>intVar = </code><code>123</code><code>;</code>

<code>      </code><code>StringstringVar = </code><code>"123"</code><code>;</code>

<code>      </code><code>System.out.format(Locale.FRANCE, </code><code>"The value of the float "</code> <code>+ </code><code>"variable is %f, while the "</code>

<code>                           </code><code>+ </code><code>"value of the integer variable "</code> <code>+ </code><code>"is %d, and the string is %s%n"</code><code>, floatVar, intVar, stringVar);</code>

其输出如下:

   The value of the float variable is 123,370003, while the value of the integer variable is 123, and the string is123

在这个Demo里,使用到各种常用的转化符和flags,具体解释如下表:(更多格式可参阅java.util.Formatter)

Converters and Flags Used indemo.java

转换符

Flag

说明

d

十进制数据

f

浮点数据

n

换行符。注意是用“%n”,而不是“\n”.

tB,tb

‘t’指日期/时间的转换(下同),’B’指月份全称(如January),’b’指月份的简称(如Jan)

ty, tY

格式年份,‘y’指格式化时带前导零的两位数,即00 – 99;’Y’指格式化时带前导零的四位数(至少),如0096或者2013。

tm

格式月份,’m’指格式时带前导零的两位数,即01 ~ 13.

td, te

‘t’指日期/时间的转换,’d’指一个月中的天数,在格式化时带前导零的两位数,即01 – 31;‘e’指格式化为两位数,即1 – 31。

tl,tk

格式小时数,’l’指12小时制(1 ~ 12),’k’指24小时制(0 ~ 23)。

tM

格式分钟数,’M’指格式化时带前导零的两位数,即00 ~ 59。

tS

格式化秒,格式化时带前导零的两位数,即00 - 60("60" 是支持闰秒所需的一个特殊值)。

tp

tD

A date &amp; time conversion—date as %tm%td%ty

08

8个字符宽度,宽度不足在头部以“0”填充

+

包含符号位(正数+或负数—)

,

组分隔符

-

左对齐(默认是右对齐)

.3

保留3位小数

10.3

表示10个字符宽度,保留三位小数(默认右对齐)

6

7

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<code>import</code> <code>java.util.Calendar;</code>

<code>import</code> <code>java.util.Locale;</code>

<code>public</code> <code>class</code> <code>IntegerText {</code>

<code>    </code><code>public</code> <code>static</code> <code>void</code> <code>main(String[] args) {</code>

<code>        </code><code>long</code> <code>n = </code><code>461012</code><code>;</code>

<code>        </code><code>System.out.format(</code><code>"%d%n"</code><code>, n); </code><code>// --&gt; "461012"</code>

<code>        </code><code>System.out.format(</code><code>"%08d%n"</code><code>, n); </code><code>// --&gt; "00461012"</code>

<code>        </code><code>System.out.format(</code><code>"%+8d%n"</code><code>, n); </code><code>// --&gt; " +461012"</code>

<code>        </code><code>System.out.format(</code><code>"%,8d%n"</code><code>, n); </code><code>// --&gt; " 461,012"</code>

<code>        </code><code>System.out.format(</code><code>"%+,8d%n%n"</code><code>, n); </code><code>// --&gt; "+461,012"</code>

<code>        </code><code>double</code> <code>pi = Math.PI;</code>

<code>        </code><code>System.out.format(</code><code>"%f%n"</code><code>, pi); </code><code>// --&gt; "3.141593"</code>

<code>        </code><code>System.out.format(</code><code>"%.3f%n"</code><code>, pi); </code><code>// --&gt; "3.142"</code>

<code>        </code><code>System.out.format(</code><code>"%10.3f%n"</code><code>, pi); </code><code>// --&gt; "     3.142"</code>

<code>        </code><code>System.out.format(</code><code>"%-10.3f%n"</code><code>, pi); </code><code>// --&gt; "3.142"</code>

<code>        </code><code>System.out.format(Locale.FRANCE, </code><code>"%-10.4f%n%n"</code><code>, pi); </code><code>// --&gt; "3,1416"</code>

<code>        </code><code>Calendar c = Calendar.getInstance();</code>

<code>        </code><code>System.out.format(</code><code>"%tB %te, %tY%n"</code><code>, c, c, c); </code><code>// --&gt; "May 29, 2006"</code>

<code>        </code><code>System.out.format(</code><code>"%tl:%tM %tp%n"</code><code>, c, c, c); </code><code>// --&gt; "2:34 am"</code>

<code>        </code><code>System.out.format(</code><code>"%tD%n"</code><code>, c); </code><code>// --&gt; "05/29/06"</code>

<code>    </code><code>}</code>

<code>}</code>

<code>import</code> <code>java.text.*;</code>

<code>public</code> <code>class</code> <code>DecimalFormatDemo {</code>

<code>    </code><code>static</code> <code>public</code> <code>void</code> <code>customFormat(String pattern, </code><code>double</code> <code>value) {</code>

<code>        </code><code>DecimalFormat myFormatter = </code><code>new</code> <code>DecimalFormat(pattern);</code>

<code>        </code><code>String output = myFormatter.format(value);</code>

<code>        </code><code>System.out.println(value + </code><code>"  "</code> <code>+ pattern + </code><code>"  "</code> <code>+ output);</code>

<code>    </code><code>static</code> <code>public</code> <code>void</code> <code>main(String[] args) {</code>

<code>        </code><code>customFormat(</code><code>"###,###.###"</code><code>, </code><code>123456.789</code><code>);    </code><code>//--&gt;123456.789  ###,###.###  123,456.789</code>

<code>        </code><code>customFormat(</code><code>"###.##"</code><code>, </code><code>123456.789</code><code>);         </code><code>//--&gt;123456.789  ###.##  123456.79</code>

<code>        </code><code>customFormat(</code><code>"00.000"</code><code>, </code><code>123.7876</code><code>);           </code><code>//--&gt;123.7876  00.000  123.788</code>

<code>        </code><code>customFormat(</code><code>"$###,###.###"</code><code>, </code><code>12345.67</code><code>);     </code><code>//--&gt;12345.67  $###,###.###  $12,345</code>

<code>DecimalFormat.java</code>输出说明

数值

Pattern

输出

123456.789

###,###.###

123,456.789

‘#’ 代表了一个阿拉伯数字,‘,’为组分隔符,‘.’用于分割整数和小数

###.##

123456.79

数值有三位小数,而模式里只用两个,会通过四舍五入保留两位小数

123.78

000000.000

‘0’代表了一个阿拉伯数字,位数不足需要在前或后一零补充,注意其与‘#’的区别。

12345.67

$###,###.###

$12,345.67

以美元符号‘$’开头,保留三位小数,且组分割为3

tips:组分隔符“,”通常用于千位,但是在某些国家/地区中回用于分隔万位(如中国)。分组大小是分组字符之间的固定数字位数,例如100,000,000 是 3,而 1,0000,0000 则是 4。如果使用具有多个分组字符的模式,则最后一个分隔符和整数结尾之间的间隔才是使用的分组大小。所以 "#,##,###,####" == "######,####" =="##,####,####"。 即“123456.789”的模式为“###,#,##.###”,其输出为“12,34,56.789”。

在Math类里包含两个常量:

Math.E,     自然底数e

Math.PI,圆周率

Math类包含了超过40个的静态方法,为了分类来谈,先列出Math里的基本算术方法:

Math的基本算术方法

double abs(double d)

float abs(float f)

int abs(int i)

long abs(long lng)

返回参数的绝对值

double ceil(double d)

取得大于或等于参数的最小整数,并以double类型返回

double floor(double d)

取得小于或等于参数的最大整数,并以double类型返回

double rint(double d)

取得最接近参数的某一整数(类似于四舍五入),并以double类型返回

long round(double d)

int round(float f)

返回最接近参数的<code>long/int</code><code>值</code>。

double min(double arg1, double arg2)

float min(float arg1, float arg2)

int min(int arg1, int arg2)

long min(long arg1, long arg2)

返回两个数中较小的那一个

double max(double arg1, double arg2)

float max(float arg1, float arg2)

int max(int arg1, int arg2)

long max(long arg1, long arg2)

返回两个数中较大的那一个

BasicMathDemo演示了如何去使用Math的基本算术方法:

23

24

25

<code>public</code> <code>class</code> <code>BasicMathDemo {</code>

<code>     </code><code>public</code> <code>static</code> <code>void</code> <code>main(String[] args) {</code>

<code>            </code><code>double</code> <code>a = -</code><code>191.635</code><code>;</code>

<code>            </code><code>double</code> <code>b = </code><code>43.74</code><code>;</code>

<code>            </code><code>int</code> <code>c = </code><code>16</code><code>, d = </code><code>45</code><code>;</code>

<code>            </code><code>System.out.printf(</code><code>"The absolute value "</code> <code>+</code>

<code>                              </code><code>"of %.3f is %.3f%n"</code><code>,</code>

<code>                              </code><code>a, Math.abs(a));      </code><code>//--&gt;The absolute value of -191.635 is 191.635</code>

<code>            </code><code>System.out.printf(</code><code>"The ceiling of "</code> <code>+</code>

<code>                              </code><code>"%.2f is %.0f%n"</code><code>,</code>

<code>                              </code><code>b, Math.ceil(b));     </code><code>//--&gt;The ceiling of 43.74 is 44</code>

<code>            </code><code>System.out.printf(</code><code>"The floor of "</code> <code>+</code>

<code>                              </code><code>b, Math.floor(b));    </code><code>//--&gt;The floor of 43.74 is 43</code>

<code>            </code><code>System.out.printf(</code><code>"The rint of %.2f "</code> <code>+</code>

<code>                              </code><code>"is %.0f%n"</code><code>,</code>

<code>                              </code><code>b, Math.rint(b));     </code><code>//--&gt;The rint of 43.74 is 44</code>

<code>            </code><code>System.out.printf(</code><code>"The max of %d and "</code> <code>+</code>

<code>                              </code><code>"%d is %d%n"</code><code>,</code>

<code>                              </code><code>c, d, Math.max(c, d));</code><code>//--&gt;The max of 16 and 45 is 45</code>

<code>            </code><code>System.out.printf(</code><code>"The min of of %d "</code> <code>+</code>

<code>                              </code><code>"and %d is %d%n"</code><code>,</code>

<code>                              </code><code>c, d, Math.min(c, d));</code><code>//--&gt;The min of of 16 and 45 is 16</code>

<code>        </code><code>}</code>

下表列出了在Math里关于指数与对数运算的方法:

指数、对数运算的方法

double exp(double d)

返回自然底数e的d次方幂的值

double log(double d)

double pow(double base, double exponent)

返回base的exponent次方的值

double sqrt(double d)

返回d的算术平方根

<code>public</code> <code>class</code> <code>ExponentialDemo {</code>

<code>        </code><code>double</code> <code>x = </code><code>11.635</code><code>;</code>

<code>        </code><code>double</code> <code>y = </code><code>2.76</code><code>;</code>

<code>        </code><code>System.out.printf(</code><code>"The value of "</code> <code>+</code>

<code>                          </code><code>"e is %.4f%n"</code><code>,</code>

<code>                          </code><code>Math.E);      </code><code>//--&gt;The value of e is 2.7183</code>

<code>        </code><code>System.out.printf(</code><code>"exp(%.3f) "</code> <code>+</code>

<code>                          </code><code>"is %.3f%n"</code><code>,</code>

<code>                          </code><code>x, Math.exp(x));</code><code>//--&gt;exp(11.635) is 112983.831</code>

<code>        </code><code>System.out.printf(</code><code>"log(%.3f) is "</code> <code>+</code>

<code>                          </code><code>"%.3f%n"</code><code>,</code>

<code>                          </code><code>x, Math.log(x));</code><code>//--&gt;log(11.635) is 2.454</code>

<code>        </code><code>System.out.printf(</code><code>"pow(%.3f, %.3f) "</code> <code>+</code>

<code>                          </code><code>x, y, Math.pow(x, y));</code><code>//--&gt;pow(11.635, 2.760) is 874.008</code>

<code>        </code><code>System.out.printf(</code><code>"sqrt(%.3f) is "</code> <code>+</code>

<code>                          </code><code>x, Math.sqrt(x));</code><code>//--&gt;sqrt(11.635) is 3.411</code>

下表列出了Math里关于三角函数的方法,需要注意的是,这些方法的参数都是以弧度制来表示的——换句话说就是,你需要将角度转换为弧度。可以使用方法toRadians(),将角度转换为弧度。

三角函数运算的方法

double sin(double d)

返回角的三角正弦值

double cos(double d)

返回角的三角余弦值

double tan(double d)

返回角的三角正切值

double asin(double d)

返回一个值的反正弦值;返回的角度范围在 -pi/2 到pi/2  之间。

double acos(double d)

返回一个值的反余弦值;返回的角度范围在 0.0 到pi之间。

double atan(double d)

返回一个值的反正切值;返回的角度范围在 -pi/2 到pi/2  之间。

double atan2(double y, double x)

将矩形坐标 (<code>x</code>, <code>y</code>) 转换成极坐标 (r, theta),返回所得角theta值。

double toDegrees(double d)

 double toRadians(double d)

角度和与弧度的相互转换方法

26

27

28

29

30

31

32

33

34

<code>public</code> <code>class</code> <code>TrigonometricDemo {</code>

<code>            </code><code>double</code> <code>degrees = </code><code>45.0</code><code>;</code>

<code>            </code><code>double</code> <code>radians = Math.toRadians(degrees);</code>

<code>                                                                 </code> 

<code>            </code><code>System.out.format(</code><code>"The value of pi "</code> <code>+</code>

<code>                              </code><code>"is %.4f%n"</code><code>,Math.PI);</code>

<code>            </code><code>//--&gt;The value of pi is 3.1416</code>

<code>            </code><code>System.out.format(</code><code>"The sine of %.1f "</code> <code>+</code>

<code>                              </code><code>"degrees is %.4f%n"</code><code>,</code>

<code>                              </code><code>degrees,Math.sin(radians));</code>

<code>            </code><code>//--&gt;The sine of 45.0 degrees is 0.7071</code>

<code>            </code><code>System.out.format(</code><code>"The cosine of %.1f "</code> <code>+</code>

<code>                              </code><code>degrees, Math.cos(radians));</code>

<code>            </code><code>//--&gt;The cosine of 45.0 degrees is 0.7071</code>

<code>            </code><code>System.out.format(</code><code>"The tangent of %.1f "</code> <code>+</code>

<code>                              </code><code>degrees, Math.tan(radians));</code>

<code>            </code><code>//--&gt;The tangent of 45.0 degrees is 1.0000</code>

<code>            </code><code>System.out.format(</code><code>"The arcsine of %.4f "</code> <code>+</code>

<code>                              </code><code>"is %.4f degrees %n"</code><code>,</code>

<code>                              </code><code>Math.sin(radians), Math.toDegrees(Math.asin(Math.sin(radians))));</code>

<code>            </code><code>//--&gt;The arcsine of 0.7071 is 45.0000 degrees</code>

<code>            </code><code>System.out.format(</code><code>"The arccosine of %.4f "</code> <code>+</code>

<code>                              </code><code>Math.cos(radians),  Math.toDegrees(Math.acos(Math.cos(radians))));</code>

<code>            </code><code>//--&gt;The arccosine of 0.7071 is 45.0000 degrees</code>

<code>            </code><code>System.out.format(</code><code>"The arctangent of %.4f "</code> <code>+</code>

<code>                              </code><code>Math.tan(radians), Math.toDegrees(Math.atan(Math.tan(radians))));</code>

<code>            </code><code>//--&gt;The arctangent of 1.0000 is 45.0000 degrees</code>

      Math类的random()方法可以产生大于等于<code>0.0</code>且小于<code>1.0</code><code>的(伪)随机数(0 &lt;= Math.random()&lt;1),如此,你便能利用这个函数产生各中范围的随机数,如</code>

<code>要产生0~9的随机数:</code>

<code>int</code> <code>number = (</code><code>int</code><code>)(Math.random() * </code><code>10</code><code>);       </code><code>//(0 &lt;= number &lt; 10)</code>

如产生5~9的随机数:

<code>int</code> <code>number = (</code><code>int</code><code>)(Math.random() * </code><code>5</code><code>) + </code><code>5</code><code>;</code>

附:使用Math.random()可以产生一个随机数。如果需要产生一系列随机数,可以创建 java.util.Random的对象,并调用对应的方法。

本文转自peiquan 51CTO博客,原文链接:http://blog.51cto.com/peiquan/1282169