diff --git a/poincare/include/poincare/decimal.h b/poincare/include/poincare/decimal.h index 14472eb2b..bc315f0d7 100644 --- a/poincare/include/poincare/decimal.h +++ b/poincare/include/poincare/decimal.h @@ -31,6 +31,7 @@ private: /* Sorting */ int compareToSameTypeExpression(const Expression * e) const override; + constexpr static int k_maxLength = 10; Integer m_mantissa; int m_exponent; }; diff --git a/poincare/src/decimal.cpp b/poincare/src/decimal.cpp index baaea302c..ddc59d0a6 100644 --- a/poincare/src/decimal.cpp +++ b/poincare/src/decimal.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include extern "C" { #include @@ -90,6 +91,34 @@ int Decimal::writeTextInBuffer(char * buffer, int bufferSize) const { } buffer[bufferSize-1] = 0; int currentChar = 0; + if (currentChar >= bufferSize-1) { return bufferSize-1; } + if (m_mantissa.isZero()) { + buffer[currentChar++] = '0'; + buffer[currentChar] = 0; + return currentChar; + } + int nbOfDigitsInMantissa = numberOfDigitsInMantissa(); + int numberOfRequiredDigits = nbOfDigitsInMantissa > m_exponent ? nbOfDigitsInMantissa : m_exponent; + numberOfRequiredDigits = m_exponent < 0 ? 1+nbOfDigitsInMantissa-m_exponent : numberOfRequiredDigits; + /* The number would be too long if we print it as a natural decimal */ + if (numberOfRequiredDigits > k_maxLength) { + if (nbOfDigitsInMantissa == 1) { + currentChar +=m_mantissa.writeTextInBuffer(buffer, bufferSize); + } else { + currentChar++; + currentChar += m_mantissa.writeTextInBuffer(buffer+currentChar, bufferSize-currentChar); + buffer[0] = buffer[1]; + buffer[1] = '.'; + } + if (m_exponent == 0) { + return currentChar; + } + if (currentChar >= bufferSize-1) { return bufferSize-1; } + buffer[currentChar++] = Ion::Charset::Exponent; + currentChar += Integer(m_exponent).writeTextInBuffer(buffer+currentChar, bufferSize-currentChar); + return currentChar; + } + /* Print a natural decimal number */ if (m_exponent < 0) { for (int i = 0; i <= -m_exponent; i++) { if (currentChar >= bufferSize-1) { return bufferSize-1; }