diff --git a/flang/runtime/edit-output.cpp b/flang/runtime/edit-output.cpp index 57641dd4da8c4..6ccaa00a16302 100644 --- a/flang/runtime/edit-output.cpp +++ b/flang/runtime/edit-output.cpp @@ -419,15 +419,22 @@ bool RealOutputEditing::EditFOutput(const DataEdit &edit) { canIncrease = false; // only once continue; } else if (expo == -fracDigits && convertedDigits > 0) { - if (rounding != decimal::FortranRounding::RoundToZero) { - // Convert again without rounding so that we can round here - rounding = decimal::FortranRounding::RoundToZero; - continue; - } else if (converted.str[signLength] >= '5') { - // Value rounds up to a scaled 1 (e.g., 0.06 for F5.1 -> 0.1) + if ((rounding == decimal::FortranRounding::RoundUp && + *converted.str != '-') || + (rounding == decimal::FortranRounding::RoundDown && + *converted.str == '-') || + (rounding == decimal::FortranRounding::RoundToZero && + rounding != edit.modes.round && // it changed below + converted.str[signLength] >= '5')) { + // Round up/down to a scaled 1 ++expo; convertedDigits = 0; trailingOnes = 1; + } else if (rounding != decimal::FortranRounding::RoundToZero) { + // Convert again with truncation so first digit can be checked + // on the next iteration by the code above + rounding = decimal::FortranRounding::RoundToZero; + continue; } else { // Value rounds down to zero expo = 0;