atof only returns integers? - c++

I've got a routine which gets numbers in the exponent format(e.g. 2,5E-02 or 4E+06) as a QString. When I print the values I always only get integers and when they are smaller then 1 I always get 0.
Does anyone know what I am doing wrong here?
(with the cout line I only wanted to test whether the QString::number() is ruining it for me)
here is a code snippet:
QStringList valPair;
value = atof(valPair[0].replace(",",".").toAscii());
value1 =atof(valPair[1].replace(",",".").toAscii());
strValue = "[" + QString::number(value) + ", " + QString::number(value1) + "]";
//cout<<value<<" "<<value1;
I'd appreciate any help!
EDIT: It was a Problem with variable declaration...
double value, value1;

Why are you doing all that work? Qt already has what you're looking for if you use QString::toDouble and QString::number(). If you set your locale manually before calling toDouble() then you can use the comma decimal notation without replacing anything.
You could also create a string template like QString("[%1,%2]") and then use the double version of QString::arg.

The conversion function doesn't support your locale, which uses comma as a decimal separator. Use 2.4e4 instead.

Related

How to convert a floating point number into a string with precision? Arduino C++

I have a number like 3.14159 and I want it to be 3.1
Arduino is being fussy with libraries for some reason. At the moment I can't use the string library.
I ended up finding an awesome solution to this. Turns out Arduino has a method for this! It's just the String() method. So in order to convert 3.14159 simply type ⤵︎
float num = 3.14159
String str1 = String(num, 1) // 3.1
String str2 = String(num, 2) // 3.14
String str3 = String(num, 3) // 3.141
So on the right of the comma is the decimal places parameter. It has a lot of functionality but that's one of the overloads. You can see them all here!
As by default sprintf does not support floats in a standard Arduino environment, there's dtostrf() coming with avr-gcc, which does what you want. Sample usage here

accessing a strings elements using [] prints random results

So, I am making a mid square hashing function as part of a project for school, and I am perplexed how my computer is taking two random string elements out of a string when I am only asking for one element. Here is a tiny example in code below.
string squaredKey = "54756";
int middleDigit = (ceil(stringSquareKey.length()/2));
cout << squaredKey[middleDigit] << endl; // this prints out 7 as expected
string temp = to_string(squaredKey[middleDigit]);
cout << temp << endl; // This prints out 55 for some reason.
I don't know exactly what the problem is, but I think it has something to do with to_string(). Let me know if you would like to see more code.
std::to_string is for converting numbers to strings. And an unfortunate fact of C++ is that char is also a number in its own right, though it's commonly used to represent ASCII values.
What to_string(squaredKey[middleDigit]); is doing is taking the ASCII value '7' (not 7) and converting it to a decimal number, which is 55.
You should use the std::string constructor that accepts a char and a count:
std::string temp(1, squaredKey[middleDigit]);
std::to_string converts a numeric value to std::string, so its input is treated as a numeric value. stringSquareKey.length()/2 gives character value '7', which corresponds - when treated as a numeric value - to ASCII code 55.
So your code is the same as string temp = to_string(55).

c++ convert integer to 8 char hex, drop the first two char so that it is only a 6 char hex, and convert back to an integer

I have been searching and experimenting for many, many, hours now, and so far I have not been able to adapt any of the solutions I have come across to do what I want.
My goal is to take an integer (538214658) and convert it into an 8 character hex string (020148102). Then I want to drop the first two characters (0148102) and convert it back into an integer(1343746) which I am using as a key in a map array.
The solutions I've seen so far just convert an integer into hex string, but don't take into account the desired digit length.
I am able to print out just the first 6 characters using the following code:
Console_Print("%06X", form ? form->refID : 0)
So I thought that maybe I could use that technique to store it into a string, and then use iostream or sstream to convert it back to an integer, but none of my searches turned up anything I could use. And all of my experiments have failed.
Some help would be greatly appreciated.
EDIT: Below is my solution based on Klaus' suggestion:
uint32_t GetCoreRefID(TESForm* form)
{
uint32_t iCoreRefID = 0;
if (form)
{
uint32_t iRefID = (uint32_t)(form->refID);
iCoreRefID = iRefID & 0x00ffffff;
}
return iCoreRefID;
}
There is no need to convert to a string representation.
Look the following example:
int main()
{
uint32_t val = 538214658 & 0x00ffffff;
std::cout << std::hex << val << std::endl;
std::cout << std::dec << val << std::endl;
}
You have to learn that a value is still only a value and is not dependent on the representation like decimal or hex. The value stored in a memory area or a register is still the same.
As you can see in the given example I wrote your decimal value representation and remove the first two hexadecimal digits simply by do a bitwise and operation with the hexadecimal representation of a mask.
Furthermore you have to understand that the printing with cout in two different "modes" did not change the value at all and also not the internal representation. With std::dec and std::hex you tell the ostream object how to create a string from an int representation.

C++ String to double atof conversion losing precision?

C++ is not my language so forgive this simple problem. I'm losing precision in an atof conversion from string to double, can anyone help?
string lAmount;
string lSuspendedInt = "131663.51";
string lAccruedInterest = "0.0";
double dSuspendedInt= atof(lSuspendedInt.c_str()); //PROBLEM HERE?
double dAccruedInterest = atof(lAccruedInterest.c_str());
double dTotal = dSuspendedInt + dAccruedInterest;
char cAmount[50];
memset(cAmount,0X00,sizeof(cAmount));
sprintf(cAmount,"%g*",dTotal);
lAmount = cAmount;
cout << "lAmount: "<<lAmount<<endl; //PRINTING: 131664 not 131663.51
I've played with %f in the memset function however this gives 131663.510000
Thanks in advance.
Sapatos
The problem is your %g format operator, which isn't specified with enough precision. You might want %.2f instead, which prints two digits after the decimal point.
The sprintf %g format specifier defaults to printing six significant digits. If you want more, you can explicitly specify how many should be printed:
sprintf(cAmount,"%.8g*",dTotal);
The function atof creates a double. See here. Your problem is that the %g returns either the shorter of float or scientific notation. See here. Also note, that you're adding the in * notation which signifies that there is an expected truncation in the number of printed characters.

How to convert a string representing decimal number in exponential form to float in Qt?

I have some decimal numbers in a text file represented in exponential form Eg: 144.2e-3. I want to store the values in float. In qt it returns "0" when i directly use the "number.toFloat()" method. Please help.
toFloat() should work. Check that your string contains only the number. If the string contains something else too, for example "144.2e-3 a", then the toFloat() returns 0. Note that also other numbers in the string will cause the conversion to fail, for example QString("144.2e-3 100").toFloat() will return 0.
Additional whitespace in the number string doesn't matter, but other characters do.
value = 3.91e+01;
double doubleValue;
stringstream valuestream(value);
valuestream >> doubleValue;
Using a stringstream you can convert exponential number to the datatype we require.
Use QString::toDouble.
Example:
bool ok;
float f = static_cast< float>( QString( "1234.56e-02" ).toDouble( &ok));