C++ std::setprecision in C# -
i'm picking c# porting legacy c++ code , keep output identical. used along lines of
output << std::setprecision(10) << (double) value;
i figured be
output.write("{0:f10}", value);
but didn't trick. values > 1
more digits. common online suggestion math.round
first, appends zeroes if total length < 10
.
so put together:
// std::setprecision not same ":f10", mirror original behavior static string setprecision(double value) { string ret = value.tostring(); // don't substring(0, 11), need apply rounding, // , don't this, don't want append zeroes, // 10 digits + period, 0.. not counting total if(ret.length > digits + 1) ret = math.round(value, digits + (value < 1 ? 1 : 0) - ret.indexof('.')).tostring(); return ret; }
where digits
static constant; make variable, project in particular makes little sense so.
still, seems overly complicated. there more elegant way traditional behavior?
as requested example i/o
// c++ double test = 0; out << std::setprecision(10); test = 0.123456780; out << test << '\n'; test = 0.0123456781; out << test << '\n'; test = 0.11234567819; out << test << '\n'; test = 1.00234567899; out << test << '\n'; // c# double test = 0; test = 0.123456780; output.writeline(setprecision(test)); test = 0.0123456781; output.writeline(setprecision(test)); test = 0.11234567819; output.writeline(setprecision(test)); test = 1.00234567899; output.writeline(setprecision(test));
both produce:
0.12345678 0.0123456781 0.1123456782 1.002345679
and meanwhile noticed heading zeroes don't seem count towards total rather first;
// c++ test = 0.012345678906; out << test << '\n'; // 0.01234567891 test = 0.0012345678906; out << test << '\n'; // 0.001234567891 test = 0.00012345678906; out << test << '\n'; // 0.0001234567891 // c# test = 0.012345678906; output.writeline(setprecision(test)); // 0.0123456789 test = 0.0012345678906; output.writeline(setprecision(test)); // 0.0012345679 test = 0.00012345678906; output.writeline(setprecision(test)); // 0.0001234568
i'll have correct if there isn't more straightforward solution.
it sounds want print number specific number of significant digits. can use g format string specify number of digits use.
output.write("{0:g10}", value);
Comments
Post a Comment