Multiple implementations of Flutter decimal rounding & keep n places after the decimal point

Multiple implementations of Flutter decimal rounding & keep n places after the decimal point


In Flutter, if we are dealing with decimals, we want to discard the decimal part, or we want to keep a few places after the decimal point, what should we do?

Discard the decimal part (round up)

First, let's see how to keep only integer bits. There are many ways to achieve this:

double price = 100 / 3;

//舍弃当前变量的小数部分,结果为 33。返回值为 int 类型。
price.truncate();
//舍弃当前变量的小数部分,浮点数形式表示,结果为 33.0。返回值为 double。
price.truncateToDouble();
//舍弃当前变量的小数部分,结果为 33。返回值为 int 类型。
price.toInt();
//小数部分向上进位,结果为 34。返回值为 int 类型。
price.ceil();
//小数部分向上进位,结果为 34.0。返回值为 double。
price.ceilToDouble();
//当前变量四舍五入后取整,结果为 33。返回值为 int 类型。
price.round();
//当前变量四舍五入后取整,结果为 33.0。返回值为 double 类型。
price.roundToDouble();

According to your own needs, whether you need rounding, etc., just choose an appropriate method.

Keep n places after the decimal point

If we want to control the precision of floating-point numbers and want to keep a few digits after the decimal point, how to achieve it?

The easiest is to use the toStringAsFixed() method:

double price = 100 / 3;
//保留小数点后2位数,并返回字符串:33.33。
price.toStringAsFixed(2);
//保留小数点后5位数,并返回一个字符串 33.33333。
price.toStringAsFixed(5);

Note that the toStringAsFixed() method performs rounding.

Or you can use a third-party class library, or write a function implementation yourself. Of course, in most cases, the toStringAsFixed() method can meet our needs.


**PS: Click me! I point! I point! …… --> "Flutter Development"
**PS: Click me! I point! I point! …… --> "Flutter Development"
**PS: More, for more content, please check --> "Flutter Development"

Guess you like

Origin blog.csdn.net/u011578734/article/details/112251314