0

Example:

float x = 3154681.124 / 100000; //x = 31.54;

I want x to be:

x = 31.5468112;
2
  • 2
    When you write 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 instead 31.54681124 you have a single rounding error, and the total error is 25% lower. May 10, 2016 at 12:01
  • 1
    An IEEE 32 bit float has only 23 bits for the fractional part, so you only get about log(2^23)/log(10)=6.9 decimal places total. Maybe you want a double?
    – Dave X
    May 12, 2016 at 16:46

2 Answers 2

1

The 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
2
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);
3
  • I don't want to print x , I want to send it as a parameter in URL to web service. when I send it as x its value became 31.54
    – Amir Hamdy
    May 9, 2016 at 21:03
  • Then whatever your code is that is doing the sending is truncating it. I can't see that code, so I can't advise on it. The simple fact, though, is a float doesn't have a fixed number of decimal places, that's not how floats work.
    – Majenko
    May 9, 2016 at 21:04
  • 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.
    – Nick Gammon
    May 10, 2016 at 5:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.