Example:
float x = 3154681.124 / 100000; //x = 31.54;
I want x to be:
x = 31.5468112;
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.
Sign up to join this communityThe float
type has slightly over 7 digits of precision. See https://en.wikipedia.org/wiki/Floating_point.
I want x to be:
x = 31.5468112;
Bad luck. That's 9 digits of precision. You can get around 7 digits by converting it appropriately, eg. as Majenko said:
float x = 3154681.124 / 100000; //x = 31.54;
Serial.println(x, 7);
However that printed:
31.5468101
It got 7 digits right, as advertised.
You can use the BigNumber Library that I wrote. Available from GitHub.
Using that, you can get all the precision you want, within reason:
#include "BigNumber.h"
void setup ()
{
Serial.begin (115200);
Serial.println ();
BigNumber::begin (7); // 7 digits after the decimal place
BigNumber x ("3154681.124");
BigNumber y = x / BigNumber ("100000");
Serial.println(y);
} // end of setup
void loop ()
{
} // end of loop
Output:
31.5468112
float x = 3154681.124 / 100000; //x = 31.54;
x
is now 31.5468112
(or close to).
Serial.println(x);
Output: 31.54
Why? Because Serial.println
defaults to 2 decimal places for floats.
Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
val
: the value to print - any data type
format
: specifies the number base (for integral data types) or number of decimal places (for floating point types)
So the solution: specift 7 decimal places when you print:
Serial.println(x, 7);
31.54
May 9, 2016 at 21:03
when I send it as x its value became 31.54
- you need to post that code. We can't answer questions about code we can't see.
3154681.124 / 100000
, you are accumulating two rounding errors: first, in representing the numerator as a float, then in the division. Total error ≈ 1.09e-6. If you write instead31.54681124
you have a single rounding error, and the total error is 25% lower.