在飞镖扩展中将双精度转换为工程符号

Convert double to engineering notation in dart extension

String floatToEngineering(double x) {
 int exp = 0, sign = 1;
  if (x < 0.0) { 
  x = -x; sign = -sign; } 
    while (x >= 1000.0) {
  x /= 1000.0; exp += 3; } 
   while (x < 1.0) {
 x *= 1000.0; exp -= 3; }
 if (sign < 0) x = -x; 
  return "${x.toStringAsFixed(4)}" + "e+" + "$exp"; }
   

该函数工作正常但没有给出长值的准确答案

      extension EngineeringNotation on double {
         String toStringAsEngineering() {
            var expString = this.toStringAsExponential();
          var eIndex = expString.lastIndexOf("e");
if (eIndex < 0) return expString; // Not exponential.
var expIndex = eIndex + 1;
if (expString.startsWith("+", expIndex)) expIndex += 1;
var exponent = int.parse(expString.substring(expIndex));

var shift = exponent % 3; // 0, 1 or 2.
if (shift == 0) return expString; // Already multiple of 3
exponent -= shift;
var dotIndex = expString.indexOf(".");
int integerEnd;
int fractionalStart;
if (dotIndex < 0) {
  integerEnd = eIndex;
  fractionalStart = eIndex;
} else {
  integerEnd = dotIndex;
  fractionalStart = dotIndex + 1;
}
var preDotValue = expString.codeUnitAt(integerEnd - 1) ^ 0x30;
while (shift > 0) {
  shift--;
  preDotValue *= 10;
  if (fractionalStart < eIndex) {
    preDotValue += expString.codeUnitAt(fractionalStart++) ^ 0x30;
  }
}
return "${integerEnd > 1 ? '-' : ''}$preDotValue."
    "${expString.substring(fractionalStart, eIndex)}e${exponent >= 0 ? '+' : ''}$exponent";

} }

这是将为您完成所有工作的扩展程序