create doubleToString and use it to convert doubles

This commit is contained in:
Wroclaw 2022-05-26 13:57:30 +02:00
parent c1b63ea2de
commit 59d9ddd593
2 changed files with 29 additions and 5 deletions

View file

@ -1,11 +1,12 @@
#include <iostream>
#include <sstream>
#include "calculator.cpp"
#include "commands.cpp"
#include "cursor.cpp"
#include "debug.cpp"
#include "getch.h"
#include "terminal.cpp"
#include "utils.cpp"
#include "calculator.cpp" //doesn't compile when sorted alphabetically, why??
/**
* @brief Prints entered keys to the console.
@ -76,9 +77,7 @@ void writeResultLine(
* @param inputSize the current input size (used to where display missing paranthesis)
*/
void writeResultLine(Calculator::parseAndCalculateResult result, const unsigned int inputSize) {
std::stringstream result_string;
result_string << result.value;
writeResultLine(result_string.str(), result.unmatchedParanthesis, result.valid, inputSize);
writeResultLine(doubleToString(result.value, 10), result.unmatchedParanthesis, result.valid, inputSize);
}
int main() {
@ -93,6 +92,8 @@ int main() {
}
#endif
std::setlocale(LC_ALL, "");
std::cout << "type your equation to calculate,\n";
std::cout << "press enter to enter a new one\n";
std::cout << "type :q to exit, type :h for help\n";
bool exit = false; //should we exit?
@ -129,7 +130,7 @@ int main() {
terminal::key_backspace(keys);
break;
case 13: // ENTER
std::cout << "\n\033[2K" << Calculator::parseAndCaluclate(keys.keys, true).value << "\n";
std::cout << "\n\033[2K" << doubleToString(Calculator::parseAndCaluclate(keys.keys, true).value, -1) << "\n";
keys.cursorPos = 0;
keys.keys.clear();
break;

23
src/utils.cpp Normal file
View file

@ -0,0 +1,23 @@
#ifndef __UTILS_CPP
#define __UTILS_CPP
#include <iomanip>
#include <sstream>
#include <limits>
/**
* @brief converts double to string
*
* @param from the double to convert
* @param precision what precision the stringed version should be
* @return std::string the converted number
*/
std::string doubleToString(const double& from, const int& precision = 10) {
std::stringstream theStream;
if (precision < 0) theStream << std::setprecision(std::numeric_limits<double>::digits10+1);
else theStream << std::setprecision(precision);
theStream << from;
return theStream.str();
}
#endif