【问题标题】:Convert double to engineering notation in dart extension在飞镖扩展中将双精度转换为工程符号
【发布时间】:2021-12-16 11:17:22
【问题描述】:
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"; }
   

该函数运行良好,但没有给出长值的准确答案

【问题讨论】:

    标签: flutter notation


    【解决方案1】:
          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";
    

    } }

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 2011-02-27
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多