简体   繁体   English

如何在小数点后将 Dart 中的双精度四舍五入到给定的精度?

[英]How do you round a double in Dart to a given degree of precision AFTER the decimal point?

Given a double, I want to round it to a given number of points of precision after the decimal point , similar to PHP's round() function.给定一个双精度数,我想将它四舍五入到小数点后给定的精度点数,类似于 PHP 的 round() 函数。

The closest thing I can find in the Dart docs is double.toStringAsPrecision(), but this is not quite what I need because it includes the digits before the decimal point in the total points of precision.我在 Dart 文档中可以找到的最接近的东西是 double.toStringAsPrecision(),但这并不是我所需要的,因为它包括总精度点中小数点的数字。

For example, using toStringAsPrecision(3):例如,使用 toStringAsPrecision(3):

0.123456789 rounds to 0.123  
9.123456789 rounds to 9.12  
98.123456789 rounds to 98.1  
987.123456789 rounds to 987  
9876.123456789 rounds to 9.88e+3

As the magnitude of the number increases, I correspondingly lose precision after the decimal place.随着数字大小的增加,我相应地失去了小数点后的精度。

See the docs for num.toStringAsFixed() .请参阅num.toStringAsFixed()的文档。

String toStringAsFixed (int fractionDigits)字符串toStringAsFixed (int fractionDigits)

Returns a decimal-point string-representation of this.返回 this 的小数点字符串表示形式。

Converts this to a double before computing the string representation.在计算字符串表示之前将其转换为双精度。

  • If the absolute value of this is greater or equal to 10^21 then this methods returns an exponential representation computed by this.toStringAsExponential() .如果 this 的绝对值大于或等于 10^21,则此方法返回由this.toStringAsExponential()计算的指数表示。

Examples:例子:

1000000000000000000000.toStringAsExponential(3); // 1.000e+21
  • Otherwise the result is the closest string representation with exactly fractionDigits digits after the decimal point.否则,结果是最接近的字符串表示形式,小数点后正好有 fractionDigits 数字。 If fractionDigits equals 0 then the decimal point is omitted.如果 fractionDigits 等于 0,则省略小数点。

The parameter fractionDigits must be an integer satisfying: 0 <= fractionDigits <= 20.参数 fractionDigits 必须是满足:0 <= fractionDigits <= 20 的整数。

Examples:例子:

1.toStringAsFixed(3);  // 1.000
(4321.12345678).toStringAsFixed(3);  // 4321.123
(4321.12345678).toStringAsFixed(5);  // 4321.12346
123456789012345678901.toStringAsFixed(3);  // 123456789012345683968.000
1000000000000000000000.toStringAsFixed(3); // 1e+21
5.25.toStringAsFixed(0); // 5

num.toStringAsFixed() rounds. num.toStringAsFixed()轮。 This one turns you num (n) into a string with the number of decimals you want (2), and then parses it back to your num in one sweet line of code:这会将您的 num (n) 转换为具有您想要的小数位数 (2) 的字符串,然后在一行甜蜜的代码中将其解析回您的 num:

n = num.parse(n.toStringAsFixed(2));

Above solutions do not appropriately round numbers.上述解决方案没有适当地对数字进行四舍五入。 I use:我用:

double dp(double val, int places){ 
   num mod = pow(10.0, places); 
   return ((val * mod).round().toDouble() / mod); 
}

Direct way:直接方式:

double d = 2.3456789;
String inString = d.toStringAsFixed(2); // '2.35'
double inDouble = double.parse(inString); // 2.35 

Using an extension:使用扩展:

extension Ex on double {
  double toPrecision(int n) => double.parse(toStringAsFixed(n));
}

Usage:用法:

void main() {
  double d = 2.3456789;
  double d1 = d.toPrecision(1); // 2.3
  double d2 = d.toPrecision(2); // 2.35
  double d3 = d.toPrecision(3); // 2.345
}
var price = 99.012334554;
price = price.toStringAsFixed(2);
print(price); // 99.01

That is the ref of dart.那是飞镖的参考。 ref: https://api.dartlang.org/stable/2.3.0/dart-core/num/toStringAsFixed.html参考: https ://api.dartlang.org/stable/2.3.0/dart-core/num/toStringAsFixed.html

void main() {
  int decimals = 2;
  int fac = pow(10, decimals);
  double d = 1.234567889;
  d = (d * fac).round() / fac;
  print("d: $d");
}

Prints: 1.23打印:1.23

I used the toStringAsFixed() method, to round a number to specific numbers after the decimal point EX:我使用了toStringAsFixed()方法,将数字四舍五入到小数点 EX 后的特定数字:

double num = 22.48132906

and when I rounded it to two numbers like this:当我将它四舍五入为这样的两个数字时:

print(num.toStringAsFixed(2)) ;

It printed 22.48它打印22.48

and when I rounded to one number, it printed 22.5当我四舍五入到一个数字时,它打印出22.5

The modified answer of @andyw using Dart Extension methods: @andyw 使用 Dart 扩展方法修改后的答案:

extension Precision on double {
    double toPrecision(int fractionDigits) {
        double mod = pow(10, fractionDigits.toDouble());
        return ((this * mod).round().toDouble() / mod);
    }
}

Usage:用法:

var latitude = 1.123456;
var latitudeWithFixedPrecision = latitude.toPrecision(3); // Outputs: 1.123

To round a double in Dart to a given degree of precision AFTER the decimal point, you can use built-in solution in dart toStringAsFixed() method, but you have to convert it back to double要将 Dart 中的 double 舍入到小数点后的给定精度,您可以使用 dart toStringAsFixed()方法中的内置解决方案,但您必须将其转换回 double

void main() {
  double step1 = 1/3;  
  print(step1); // 0.3333333333333333
  
  String step2 = step1.toStringAsFixed(2); 
  print(step2); // 0.33 
  
  double step3 = double.parse(step2);
  print(step3); // 0.33
}

您可以简单地将值乘以 100,然后将其四舍五入,然后再除以 100。

(number * 100).round() / 100.0;
double value = 2.8032739273;
String formattedValue = value.toStringAsFixed(3);

You can use toStringAsFixed in order to display the limited digits after decimal points.您可以使用toStringAsFixed来显示小数点后的有限位数。 toStringAsFixed returns a decimal-point string-representation. toStringAsFixed返回一个小数点字符串表示。 toStringAsFixed accepts an argument called fraction Digits which is how many digits after decimal we want to display. toStringAsFixed接受一个名为fraction Digits的参数,它是我们想要显示的小数点后的位数。 Here is how to use it.以下是如何使用它。

double pi = 3.1415926;
const val = pi.toStringAsFixed(2); // 3.14

Above solutions do not work for all cases.上述解决方案不适用于所有情况。 What worked for my problem was this solution that will round your number (0.5 to 1 or 0.49 to 0) and leave it without any decimals :对我的问题有用的是这个解决方案,它将你的数字四舍五入(0.5 到 1 或 0.49 到 0)并且不带任何小数

Input: 12.67输入: 12.67

double myDouble = 12.67;
var myRoundedNumber; // Note the 'var' datatype

// Here I used 1 decimal. You can use another value in toStringAsFixed(x)
myRoundedNumber = double.parse((myDouble).toStringAsFixed(1));
myRoundedNumber = myRoundedNumber.round();

print(myRoundedNumber);

Output: 13输出: 13

This link has other solutions too此链接也有其他解决方案

You can create a reusable function that accept numberOfDecimal you want to format & utilizing toStringAsFixed() method to format the number and convert it back to double .您可以创建一个可重用的函数,该函数接受要格式化的 numberOfDecimal利用 toStringAsFixed() 方法格式化数字并将其转换回 double

FYI, toStringAsFixed method does not round up number that ends with 5 (eg: toStringAsFixed round off 2.275 to 2.27 instead of 2.28).仅供参考,toStringAsFixed 方法不会对以 5 结尾的数字进行四舍五入(例如:toStringAsFixed 将 2.275 舍入为 2.27 而不是 2.28)。 This is the default behaviour of dart toStringAsFixed method (similar to Javascript toFixed) 这是 dart toStringAsFixed 方法的默认行为(类似于 Javascript toFixed)

As a workaround, we can add 1 to the existing number after the last decimal number (eg: Add 0.0001 to 2.275 become 2.2751 & 2.2751 will round off correctly to 2.28)作为一种解决方法,我们可以在最后一个十进制数之后将 1 添加到现有数字(例如:将 0.0001 添加到 2.275 变为 2.2751 & 2.2751 将正确四舍五入为 2.28)

double roundOffToXDecimal(double number, {int numberOfDecimal = 2}) {
  // To prevent number that ends with 5 not round up correctly in Dart (eg: 2.275 round off to 2.27 instead of 2.28)
  String numbersAfterDecimal = number.toString().split('.')[1];
  if (numbersAfterDecimal != '0') {
    int existingNumberOfDecimal = numbersAfterDecimal.length;
    number += 1 / (10 * pow(10, existingNumberOfDecimal));
  }

  return double.parse(number.toStringAsFixed(numberOfDecimal));
}

// Example of usage:
var price = roundOffToXDecimal(2.275, numberOfDecimal: 2)
print(price); // 2.28

I made this extension on double我在双重上做了这个扩展

import 'dart:math';

extension DoubleExtension on double {

  /// rounds the double to a specific decimal place
  double roundedPrecision(int places) {
    double mod = pow(10.0, places) as double;
    return ((this * mod).round().toDouble() / mod);
  }

  /// good for string output because it can remove trailing zeros
  /// and sometimes periods. Or optionally display the exact number of trailing
  /// zeros
  String roundedPrecisionToString(
    int places, {
    bool trailingZeros = false,
  }) {
    double mod = pow(10.0, places) as double;
    double round = ((this * mod).round().toDouble() / mod);
    String doubleToString =
        trailingZeros ? round.toStringAsFixed(places) : round.toString();
    if (!trailingZeros) {
      RegExp trailingZeros = RegExp(r'^[0-9]+.0+$');
      if (trailingZeros.hasMatch(doubleToString)) {
        doubleToString = doubleToString.split('.')[0];
      }
    }
    return doubleToString;
  }

  String toStringNoTrailingZeros() {
    String doubleToString = toString();
    RegExp trailingZeros = RegExp(r'^[0-9]+.0+$');
    if (trailingZeros.hasMatch(doubleToString)) {
      doubleToString = doubleToString.split('.')[0];
    }
    return doubleToString;
  }
}

Here are the passing tests.这是通过的测试。

import 'package:flutter_test/flutter_test.dart';
import 'package:project_name/utils/double_extension.dart';

void main() {
  group("rounded precision", () {
    test("rounding to 0 place results in an int", () {
      double num = 5.1234;
      double num2 = 5.8234;
      expect(num.roundedPrecision(0), 5);
      expect(num2.roundedPrecision(0), 6);
    });
    test("rounding to 1 place rounds correctly to 1 place", () {
      double num = 5.12;
      double num2 = 5.15;
      expect(num.roundedPrecision(1), 5.1);
      expect(num2.roundedPrecision(1), 5.2);
    });
    test(
        "rounding a number to a precision that is more accurate than the origional",
        () {
      double num = 5;
      expect(num.roundedPrecision(5), 5);
    });
  });

  group("rounded precision returns the correct string", () {
    test("rounding to 0 place results in an int", () {
      double num = 5.1234;
      double num2 = 5.8234;
      expect(num.roundedPrecisionToString(0), "5");
      expect(num2.roundedPrecisionToString(0), "6");
    });
    test("rounding to 1 place rounds correct", () {
      double num = 5.12;
      double num2 = 5.15;
      expect(num.roundedPrecisionToString(1), "5.1");
      expect(num2.roundedPrecisionToString(1), "5.2");
    });
    test("rounding to 2 places rounds correct", () {
      double num = 5.123;
      double num2 = 5.156;
      expect(num.roundedPrecisionToString(2), "5.12");
      expect(num2.roundedPrecisionToString(2), "5.16");
    });
    test("cut off all trailing zeros (and periods)", () {
      double num = 5;
      double num2 = 5.03000;
      expect(num.roundedPrecisionToString(5), "5");
      expect(num2.roundedPrecisionToString(5), "5.03");
    });
  });
}

Just write this extension on double只需在 double 上写这个扩展

extension Round on double {
  double roundToPrecision(int n) {
    int fac = pow(10, n).toInt();
    return (this * fac).round() / fac;
  }
}

I think the accepted answer is not the perfect solution because it converts to string .我认为接受的答案不是完美的解决方案,因为它转换为string

If you don't wanna convert to string and back to a double use double.toPrecision(decimalNumber) from GetX package.如果您不想转换为string并返回double使用GetX包中的double.toPrecision(decimalNumber)

If you don't wanna use GetX just for this (I highly recommend GetX, it will change your life with flutter) you can copy and paste this.如果你不想仅仅为此使用 GetX(我强烈推荐 GetX,它会改变你的生活)你可以复制并粘贴它。

Remeber to import the file when you wanna use the extention.当您想使用扩展时,请记住导入文件。

import 'dart:math';

extension Precision on double {
  double toPrecision(int fractionDigits) {
    var mod = pow(10, fractionDigits.toDouble()).toDouble();
    return ((this * mod).round().toDouble() / mod);
  }
}

also if you want to round the double value inside the Text.如果你想在文本中舍入双精度值。

Text('${carpetprice.toStringAsFixed(3)}',),文本('${carpetprice.toStringAsFixed(3)}',),

Rounding a double , an IEEE-754 binary floating-point number, to a specific number of decimal digits is inherently problematic.double (一个 IEEE-754二进制浮点数)四舍五入到特定数量的十进制数字本质上是有问题的。

In the same way that fractions such as 1/3 can't be exactly represented with a finite number of decimal digits, many (really infinitely many) decimal numbers can't be represented with a finite number of binary digits .就像 1/3 这样的分数不能用有限个十进制数字精确表示一样,许多(实际上是无限多个)十进制数字也不能用有限个二进制数字表示 For example, the decimal number 0.1 cannot be exactly represented in binary.例如,十进制数 0.1 不能用二进制精确表示。 While you could try to round 0.09999 to 0.1, as a double it would actually be "rounded" to 0.1000000000000000055511151231257827021181583404541015625.虽然您可以尝试将 0.09999 舍入为 0.1,但实际上将其“舍入”为double Most of the other answers that claim to round double s with decimal precision actually return the nearest representable double .声称以小数精度舍入double的大多数其他答案实际上返回最接近的可表示double

What you can do is to make the string representation look like a nice, rounded number, and that's what double.toStringAsFixed() does.可以做的是使字符串表示看起来像一个漂亮的四舍五入数字,这就是double.toStringAsFixed()所做的。 That's also why when you print 0.100000000..., you might see 0.1 if the implementation is trying to print user-friendly values.这也是为什么当您打印 0.100000000... 时,如果实现尝试打印用户友好的值,您可能会看到0.1 However, don't be fooled: the double value would never actually be 0.1 exactly, and if you do repeated arithmetic with such inexact values, you can accumulate error .但是,不要被愚弄了: double精度值实际上永远不会是 0.1,如果你用这种不精确的值重复算术,你可能会累积错误

Note that all of the above is inherent to how floating-point numbers work and is not specific to Dart.请注意,以上所有内容都是浮点数工作方式所固有的,并不是 Dart 特有的。 Also see:另见:

Bottom line: If you care about decimal precision, do NOT use binary floating-point types .底线:如果您关心十进制精度,请不要使用二进制浮点类型 This is particularly important if you're dealing with money.如果您正在处理金钱,这一点尤其重要。

You instead should use:您应该使用:

  • Integers.整数。 For example, if you are dealing with currency, instead of using double dollars = 1.23;例如,如果您正在处理货币,而不是使用double dollars = 1.23; , use int cents = 123; , 使用int cents = 123; . . Your calculations then always will be exact, and you can convert to the desired units only when displaying them to the user (and likewise can convert in the opposite direction when reading input from the user).然后,您的计算将始终是准确的,并且只有在向用户显示它们时才能转换为所需的单位(并且同样可以在读取用户的输入时以相反的方向转换)。
  • A type designed to represent decimal numbers with arbitrary precision.一种旨在以任意精度表示十进制数的类型。 For example, package:decimal provides a Decimal type.例如, package:decimal提供了Decimal类型。 With such a type, some of the other answers (such as multiplying by 100, rounding, and then dividing by 100) then would be appropriate.对于这种类型,其他一些答案(例如乘以 100、四舍五入,然后除以 100)将是合适的。 (But really you should use Decimal.round directly.) (但实际上你应该直接使用Decimal.round 。)

If you don't want any decimals when the resulting decimals are all zeroes, something like this would work:如果您在结果小数全为零时不想要任何小数,则可以使用以下方法:

String fixedDecimals(double d, int decimals, {bool removeZeroDecimals = true}){
  double mod = pow(10.0, decimals);
  double result = ((d * mod).round().toDouble() / mod);
  if( removeZeroDecimals && result - (result.truncate()) == 0.0 ) decimals = 0;
  return result.toStringAsFixed(decimals);
}

This will simply output 9 instead of 9.00 if the input is 9.004 and you want 2 decimals.如果输入是9.004并且您想要 2 个小数,这将简单地输出9而不是9.00

if use dynamic type of data.如果使用动态类型的数据。 You can use it.你可以使用它。

 typeDecimal(data) => num.parse(data.toString()).toStringAsFixed(2);

Never thought this was so complex in Dart but this is my solution:从没想过这在 Dart 中如此复杂,但这是我的解决方案:

double truncateDouble(double val, int decimals) {
    String valString = val.toString();
    int dotIndex = valString.indexOf('.');

    // not enough decimals
    int totalDecimals = valString.length - dotIndex - 1;
    if (totalDecimals < decimals) {
      decimals = totalDecimals;
    }

    valString = valString.substring(0, dotIndex + decimals + 1);

    return double.parse(valString);
  }

var val = truncateDouble(44.999, 2);

This DART rounding problem has been a long time coming ( @LucasMeadows ), since it's clear that it has not been adequately solved ( as indicated by @DeepShah's observation ) until now.这个 DART 舍入问题由来已久( @LucasMeadows ),因为很明显它直到现在还没有得到充分解决(如@DeepShah 的观察所示)。

The well-known rounding rule ( the unsolved problem ):众所周知的舍入规则(未解决的问题):

" Rounding numbers that end with the number 5: round up if the result is an even number; round down if the result is an odd number. " "以数字 5 结尾的数字四舍五入:如果结果是偶数,则四舍五入;如果结果是奇数,则四舍五入。 "

So here is the DART code solution:所以这里是 DART 代码解决方案:

double roundAccurately(double numToRound, int decimals) {

  // Step 1 - Prime IMPORTANT Function Parameters ...
  int iCutIndex = 0;
  String sDeciClipdNTR = "";
  num nMod = pow(10.0, decimals);
  String sNTR = numToRound.toString();
  int iLastDigitNTR = 0, i2ndLastDigitNTR = 0;
  print("Round => $numToRound to $decimals Decimal ${(decimals == 1) ? "Place" : "Places"} !!");   // Deactivate this 'print()' line in production code !!

  // Step 2 - Calculate Decimal Cut Index (i.e. string cut length) ...
  int iDeciPlaces = (decimals + 2);
  if (sNTR.contains('.')) {
    iCutIndex = sNTR.indexOf('.') + iDeciPlaces;
  } else {
    sNTR = sNTR + '.';
    iCutIndex = sNTR.indexOf('.') + iDeciPlaces;
  }

  // Step 3 - Cut input double to length of requested Decimal Places ...
  if (iCutIndex > sNTR.length) {                    // Check that decimal cutting is possible ...
    sNTR = sNTR + ("0" * iDeciPlaces);              // ... and fix (lengthen) the input double if it is too short.
    sDeciClipdNTR = sNTR.substring(0, iCutIndex);   // ... then cut string at indicated 'iCutIndex' !!
  } else {
    sDeciClipdNTR = sNTR.substring(0, iCutIndex);   // Cut string at indicated 'iCutIndex' !!
  }

  // Step 4 - Extract the Last and 2nd Last digits of the cut input double.
  int iLenSDCNTR = sDeciClipdNTR.length;
  iLastDigitNTR = int.parse(sDeciClipdNTR.substring(iLenSDCNTR - 1));   // Extract the last digit !!
  (decimals == 0)
    ? i2ndLastDigitNTR = int.parse(sDeciClipdNTR.substring(iLenSDCNTR - 3, iLenSDCNTR - 2))
    : i2ndLastDigitNTR = int.parse(sDeciClipdNTR.substring(iLenSDCNTR - 2, iLenSDCNTR - 1));

  // Step 5 - Execute the FINAL (Accurate) Rounding Process on the cut input double.
  double dAccuRound = 0;
  if (iLastDigitNTR == 5 && ((i2ndLastDigitNTR + 1) % 2 != 0)) {
    dAccuRound = double.parse(sDeciClipdNTR.substring(0, iLenSDCNTR - 1));
  } else {
    if (iLastDigitNTR < 5) {
      dAccuRound = double.parse(sDeciClipdNTR.substring(0, iLenSDCNTR - 1));
    } else {
      if (decimals == 0) {
        sDeciClipdNTR = sNTR.substring(0, iCutIndex - 2);
        dAccuRound = double.parse(sDeciClipdNTR) + 1;   // Finally - Round UP !!
      } else {
        double dModUnit = 1 / nMod;
        sDeciClipdNTR = sNTR.substring(0, iCutIndex - 1);
        dAccuRound = double.parse(sDeciClipdNTR) + dModUnit;   // Finally - Round UP !!
      }
    }
  }

  // Step 6 - Run final QUALITY CHECK !!
  double dResFin = double.parse(dAccuRound.toStringAsFixed(decimals));

  // Step 7 - Return result to function call ...
  print("Result (AccuRound) => $dResFin !!");   // Deactivate this 'print()' line in production code !!
  return dResFin;
}

It's a completely manual approach (and probably a bit of an overkill), but it works.这是一种完全手动的方法(可能有点矫枉过正),但它确实有效。 Please test it (to exhaustion) and let me know if I've missed the mark.请测试它(用尽),如果我错过了标记,请告诉我。

I've release a package called Fixed which is designed to fix this problem.我发布了一个名为 Fixed 的包,它旨在解决这个问题。

https://pub.dev/packages/fixed https://pub.dev/packages/fixed

Sorry, pub intended.对不起,酒吧打算。

That one too.那个也是。

Never post after midnight.切勿在午夜后发帖。

If you want use special rounding.如果你想使用特殊的舍入。 You can try this function (rounding).你可以试试这个功能(四舍五入)。

void main(List<String> arguments) {
list.map((e) {
 log('list1');
 rounding(e, 0.05);
 rounding(e, 0.1);
 rounding(e, 0.2);
 rounding(e, 0.25);
 rounding(e, 0.5);
 rounding(e, 1);
 rounding(e, 10);
}).toList();
list2.map((e) {
 log('list2');
 rounding(e, 0.05);
 rounding(e, 0.1);
 rounding(e, 0.2);
 rounding(e, 0.25);
 rounding(e, 0.5);
 rounding(e, 1);
 rounding(e, 10);
}).toList();
}

const list = [1.11, 1.22, 1.33, 1.44, 1.55, 1.66, 1.77, 1.88, 1.99];

const list2 = [2.19, 3.28, 4.37, 5.46, 6.55, 7.64, 8.73, 9.82, 10.91];

void rounding(double price, double count) {
log('-----------------------');
log('price: $price, count: $count');
double _priceRemainder = price % count;
double _someDiff = count / _priceRemainder;
log('_price: ${_priceRemainder.toStringAsFixed(2)}');
log('_pricePlus: ${_someDiff.toStringAsFixed(2)}');
if (_someDiff.toStringAsFixed(2) == '1.00') {
 log('_someDiff = 1');
} else if (_someDiff > 1 && _someDiff <= 2 ||
   _someDiff.toStringAsFixed(2) == '2.00') {
 log('_someDiff > 1 && _someDiff <= 2 || _someDiff.toStringAsFixed(2) == 2.00');
 log('ceilToDouble: $price: ${(price + (count - _priceRemainder)).toStringAsFixed(2)}');
 log('floorToDouble: $price: ${(price - _priceRemainder).toStringAsFixed(2)}');
 log('roundToDouble: $price: ${(price + (count - _priceRemainder)).toStringAsFixed(2)}');
} else if (_someDiff > 2) {
 log('_someDiff > 2');
 log('ceilToDouble: $price: ${(price + (count - _priceRemainder)).toStringAsFixed(2)}');
 log('floorToDouble: $price: ${(price - _priceRemainder).toStringAsFixed(2)}');
 log('roundToDouble: $price: ${(price - _priceRemainder).toStringAsFixed(2)}');
}
log('-----------------------');
}

Debug console:调试控制台:


[log] price: 10.91, count: 0.05
[log] _price: 0.01
[log] _pricePlus: 5.00
[log] _someDiff > 2
[log] ceilToDouble: 10.91: 10.95
[log] floorToDouble: 10.91: 10.90
[log] roundToDouble: 10.91: 10.90
2
[log] -----------------------
[log] price: 10.91, count: 0.1
[log] _price: 0.01
[log] _pricePlus: 10.00
[log] _someDiff > 2
[log] ceilToDouble: 10.91: 11.00
[log] floorToDouble: 10.91: 10.90
[log] roundToDouble: 10.91: 10.90
2
[log] -----------------------
[log] price: 10.91, count: 0.2
[log] _price: 0.11
[log] _pricePlus: 1.82
[log] _someDiff > 1 && _someDiff <= 2 || _someDiff.toStringAsFixed(2) == 2.00
[log] ceilToDouble: 10.91: 11.00
[log] floorToDouble: 10.91: 10.80
[log] roundToDouble: 10.91: 11.00
2
[log] -----------------------
[log] price: 10.91, count: 0.25
[log] _price: 0.16
[log] _pricePlus: 1.56
[log] _someDiff > 1 && _someDiff <= 2 || _someDiff.toStringAsFixed(2) == 2.00
[log] ceilToDouble: 10.91: 11.00
[log] floorToDouble: 10.91: 10.75
[log] roundToDouble: 10.91: 11.00
2
[log] -----------------------
[log] price: 10.91, count: 0.5
[log] _price: 0.41
[log] _pricePlus: 1.22
[log] _someDiff > 1 && _someDiff <= 2 || _someDiff.toStringAsFixed(2) == 2.00
[log] ceilToDouble: 10.91: 11.00
[log] floorToDouble: 10.91: 10.50
[log] roundToDouble: 10.91: 11.00
2
[log] -----------------------
[log] price: 10.91, count: 1.0
[log] _price: 0.91
[log] _pricePlus: 1.10
[log] _someDiff > 1 && _someDiff <= 2 || _someDiff.toStringAsFixed(2) == 2.00
[log] ceilToDouble: 10.91: 11.00
[log] floorToDouble: 10.91: 10.00
[log] roundToDouble: 10.91: 11.00
2
[log] -----------------------
[log] price: 10.91, count: 10.0
[log] _price: 0.91
[log] _pricePlus: 10.99
[log] _someDiff > 2
[log] ceilToDouble: 10.91: 20.00
[log] floorToDouble: 10.91: 10.00
[log] roundToDouble: 10.91: 10.00

If you need proper rounding (up when first digit is 5) and you want to have trailing 0's you can use this method:如果您需要适当的四舍五入(当第一个数字为 5 时向上)并且您想要尾随 0,您可以使用此方法:

import 'dart:math';

String customRound(double val, int places) {
  num mod = pow(10.0, places);
  return ((val * mod).round().toDouble() / mod).toStringAsFixed(places);
}

customRound(2.345) // -> 2.35
customRound(2.500) // -> 2.50

I prever converting my like this => `我喜欢这样转换我的 => `

num.tryParse("23.123456789")!.toDouble().roundToDouble()

` `

This function you can call to get degree of precision in dark(flutter).您可以调用此函数来获得黑暗(颤动)的精确度。 double eval -> double that want to convert int i -> number of decimal point to return. double eval -> double 想要转换 int i -> 要返回的小数点数。

double doubleToPrecision(double eval, int i) {
double step1 = eval;//1/3
print(step1); // 0.3333333333333333

String step2 = step1.toStringAsFixed(2);
print(step2); // 0.33

double step3 = double.parse(step2);
print(step3); // 0.33
eval = step3;
return eval; }

This works pretty well这工作得很好

var price=99.012334554
price = price.roundTodouble();
print(price); // 99.01

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM