Decimals for numeric keypad

Hey guys. I am working on a numeric keypad which needs to handle decimal values. I am having some trouble handling decimal values in the range: [-1, 0, 1]. It would seem that when I convert a string of say 0. or 0.0 into a double the toDouble() function always spits out 0. This code works for values greater than 1 or less than -1:

1
2
3
4
5
6
7
8
9
10
11
12
13
        case Decimal:
      {
        if (m_maxDecimalDigits > 0)
        {
          digit = locale.decimalPoint();

          if (!value.contains(digit))
          {
            value.append(digit);
          }
        }
        break;
      }


Is there some way I can get the toDouble() method to convert a string of say: "0.0" into a number with a decimal such as 0.0?
[Note this is C++/cli and NOT standard C++]

You can convert it to a C-string and then use atof. You can't use standard type casting because it doesn't work with std::string objects.

This works:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::string str {};
double num {};

char cstr[100] {};

std::cout << "Enter number. \n: ";
std::cin >> str;

// Convert str to a C-string
strcpy (cstr, str.c_str());

// And convert the C-string to a double.
num = atof (cstr);

std::cout << "Number: " << num << std::endl;

but it's somewhat cumbersome and complicated. If anyone has a better idea, feel free to spit it out!

Note: I tried reinterpret_cast and statis_cast, but those don't work. Neither does functional-style casting or c-style casting.
a string of say: "0.0" into a number with a decimal such as 0.0?


A number is just a binary representation of the number. It has no concept of displaying a number. That is display.

As C++, is this what you're after?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

int main()
{
	double num {};
	std::string str;

	std::cout << "Enter number: ";
	std::cin >> str;

	std::istringstream iss(str);

	iss >> num;

	std::cout << std::fixed << std::setprecision(1) << num << '\n';
}


Hello vysero,

You could also try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>
#include <string>

int main()
{
	double num {};
	std::string str;

	std::cout << "Enter number: ";
	std::cin >> str;

    num = stod(str);
    
	std::cout << std::fixed << std::setprecision(8) << num << '\n';
}
Enter number: 1.12345678
1.12345678

Enter number: 0.12345678
0.12345678

Enter number: -1.12345678
-1.12345678


Andy
Topic archived. No new replies allowed.