From 8ae77eb45638fc2e191b6118d4e799e483c768de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89milie=20Feral?= Date: Fri, 20 Oct 2017 11:57:10 +0200 Subject: [PATCH] [poincare] Use scientific display when decimal are too small or too big Change-Id: Ia09785f682e559d3572cb56bbb0eb2779af4d06b --- poincare/include/poincare/decimal.h | 1 + poincare/src/decimal.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) 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; }