This is a much simpler problem to my other threads, but I can't seem to find a solution to it. The short code below kinda self-describes the problem:
float test_float = 3.14159265358979323846264338;
void setup() {
Serial.begin(115200);
String test_string = String(test_float);
Serial.println(test_string);
}
void loop() { }
Code output: 3.14
It forces the float to be a maximum of 2 decimal places when converting from float to String. I want it to be as many decimal places as possible (I am aware that floating point precision is only accurate to about 6 or 7 decimal places). Only having 2 decimal places is causing issues in later code. So, does anyone know how to turn a float into a String WITHOUT this 2 decimal place limitation?
If you want to show more decimal places, you have to tell Serial.println what you want. The default is 2 decimal places.
Paul
To begin with, there is no reason whatsoever to convert a float to a String just for the purpose of printing it, the print() function can print a float directly. You do need to specify the number of decimal places you want:
Serial.print(test_float); //prints with 2 decimal places
Serial.print(test_float, 5); //prints with 5 decimal places
String test_string = String(test_float, 4); //converts to String with 4 decimal places
Only having 2 decimal places is causing issues in later code.
Is the problem related to the String only having 2 decimal places, or to test_float not giving an expected result in a calculation? You have to be careful with calculations, if some of the operands are integers and some are floats, the fractional part may be lost in an integer calculation if you don't specifically tell the compiler to do the math as floating point.
there is no reason whatsoever to convert a float to a String just for the purpose of printing it
I am converting the float to a string, and that conversion is not as accurate as I would like. It's only going to 2 decimal places while I need more. I'm not turning it to a string simply to print it, I'm turning it to a string because that's the whole issue I'm facing. Printing it after is merely to see what the result is
Is the problem related to the String only having 2 decimal places, or to test_float not giving an expected result in a calculation
The problem is the string only having 2 decimal places. test_float is completely correct and (By multiplying it by a factor of 10 or 100) can see that it is holding the data correctly
If you want to show more decimal places, you have to tell Serial.println what you want. The default is 2 decimal places.
I believe that's only when printing floats. This is a string.
String test_string = String(test_float, 4); //converts to String with 4 decimal places
THIS, THIS RIGHT HERE is exactly what I was looking for! Thankyou so much! Wonder why I couldn't find that earlier in the "String()" documentation?
Thankyou david_2018, you have helped me out IMMENSELY!