Issue
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"; }
that function is working fine but not giving the accurate answer on the long values
Solution
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";
} }
that is the extension that will do all the work for you
Answered By - Ali Hassan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.