📜  Dart编程-数字

📅  最后修改于: 2020-11-05 04:16:14             🧑  作者: Mango


飞镖编号可以归类为-

  • int-任意大小的整数。 int数据类型用于表示整数。

  • double -IEEE 754标准指定的64位(双精度)浮点数。 double数据类型用于表示小数

num类型由intdouble类型继承。飞镖核心库允许对数值进行大量操作。

声明数字的语法如下-

int var_name;      // declares an integer variable 
double var_name;   // declares a double variable 

void main() {
   // declare an integer
   int num1 = 10;             
     
   // declare a double value
   double num2 = 10.50;  

   // print the values
   print(num1);
   print(num2);
}

它将产生以下输出-

10 
10.5 

注意-如果将分数值分配给整数变量,则Dart VM将引发异常。

解析中

parse()静态函数允许将包含数字字面量的字符串解析为数字。下图演示了相同的内容-

void main() { 
   print(num.parse('12')); 
   print(num.parse('10.91')); 
}

上面的代码将导致以下输出-

12 
10.91

如果传递了数字以外的任何值,则解析函数将引发FormatException 。以下代码显示了如何将字母数字值传递给parse()函数。

void main() { 
   print(num.parse('12A')); 
   print(num.parse('AAAA')); 
}

上面的代码将导致以下输出-

Unhandled exception: 
FormatException: 12A 
#0 num.parse (dart:core/num.dart:446) 
#1 main (file:///D:/Demos/numbers.dart:4:13) 
#2 _startIsolate. (dart:isolatepatch/isolate_patch.dart:261) 
#3 _RawReceivePortImpl._handleMessage (dart:isolatepatch/isolate_patch.dart:148)

数字属性

下表列出了Dart编号支持的属性。

Sr.No Property & Description
1 hashcode

Returns a hash code for a numerical value.

2 isFinite

True if the number is finite; otherwise, false.

3 isInfinite

True if the number is positive infinity or negative infinity; otherwise, false.

4 isNan

True if the number is the double Not-a-Number value; otherwise, false.

5 isNegative

True if the number is negative; otherwise, false.

6 sign

Returns minus one, zero or plus one depending on the sign and numerical value of the number.

7 isEven

Returns true if the number is an even number.

8 isOdd

Returns true if the number is an odd number.

编号方法

以下是数字支持的常用方法列表-

Sr.No Method & Description
1 abs

Returns the absolute value of the number.

2 ceil

Returns the least integer no smaller than the number.

3 compareTo

Compares this to other number.

4 Floor

Returns the greatest integer not greater than the current number.

5 remainder

Returns the truncated remainder after dividing the two numbers.

6 Round

Returns the integer closest to the current numbers.

7 toDouble

Returns the double equivalent of the number.

8 toInt

Returns the integer equivalent of the number.

9 toString

Returns the string equivalent representation of the number.

10 truncate

Returns an integer after discarding any fractional digits.