Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. How to get value 1.3 from a float value 1.333333

How to get value 1.3 from a float value 1.333333

Scheduled Pinned Locked Moved C / C++ / MFC
tutorial
20 Posts 10 Posters 3 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Andrew Brock

    Some of the suggested answers are ok, but are lacking correct rounding.

    Luc Pattyn wrote:

    double roundToOneTenth(double number) {
    return 0.1*(int)(10.*number);
    }

    Should be:

    double RoundToOneTenth(double nNumber) {
    return (int)(10.0 * nNumber + 0.5) * 0.1;
    }

    While this solution works, it requires converting a floating point number to an integer and back to a floating point number. This is somewhat slow.

    Hans Dietrich wrote:

    double d = floor(1.333333 * 10.) / 10.;

    Should be:

    double RoundToOneTenth(double nNumber) {
    return floor(nNumber * 10.0 + 0.5) * 0.1;
    }

    This is the solution I would recommend. Note that I changed /10 to *0.1. It is faster to multiply than to divide. In a simple case like this the compiler would make this change for you but I am just pointing this out.

    Alain Rist wrote:

    #include <sstream>
    #include <iomanip>
    double Round(double val, size_t decimal)
    {
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(decimal) << val << std::ends;
    std::istringstream(oss.str()) >> val;
    return val;
    }

    While this works and saves you from worrying about rounding errors, this is incredibly slow and uses much more memory (although still not much) than other solutions. There is no need for using strings for such a simple operation. Having said that, it is good that people are posting alternatives to show just how many ways there are for doing this.

    Cedric Moonen wrote:

    Are you aware that floating points number have a rounding error ? You'll never be able to represent perfectly a float in memory.

    While this is absolutely true, it only affects really big numbers or numbers with a high precision. For instance, 1.0 / 3.0 == 0.333333333333333314829616256247390992939472198486328125 (Wikipedia[^]). If you are concerned about this, there are macros FLT_EPSILON (for float) and DLB_EPSILON (for double) which define the minimum per

    N Offline
    N Offline
    Niklas L
    wrote on last edited by
    #11

    ..and in addition, there might be other interesting aspects of rounding. This[^] post on cplusplus.com brings a few of these up.

    home

    1 Reply Last reply
    0
    • A Andrew Brock

      Some of the suggested answers are ok, but are lacking correct rounding.

      Luc Pattyn wrote:

      double roundToOneTenth(double number) {
      return 0.1*(int)(10.*number);
      }

      Should be:

      double RoundToOneTenth(double nNumber) {
      return (int)(10.0 * nNumber + 0.5) * 0.1;
      }

      While this solution works, it requires converting a floating point number to an integer and back to a floating point number. This is somewhat slow.

      Hans Dietrich wrote:

      double d = floor(1.333333 * 10.) / 10.;

      Should be:

      double RoundToOneTenth(double nNumber) {
      return floor(nNumber * 10.0 + 0.5) * 0.1;
      }

      This is the solution I would recommend. Note that I changed /10 to *0.1. It is faster to multiply than to divide. In a simple case like this the compiler would make this change for you but I am just pointing this out.

      Alain Rist wrote:

      #include <sstream>
      #include <iomanip>
      double Round(double val, size_t decimal)
      {
      std::ostringstream oss;
      oss << std::fixed << std::setprecision(decimal) << val << std::ends;
      std::istringstream(oss.str()) >> val;
      return val;
      }

      While this works and saves you from worrying about rounding errors, this is incredibly slow and uses much more memory (although still not much) than other solutions. There is no need for using strings for such a simple operation. Having said that, it is good that people are posting alternatives to show just how many ways there are for doing this.

      Cedric Moonen wrote:

      Are you aware that floating points number have a rounding error ? You'll never be able to represent perfectly a float in memory.

      While this is absolutely true, it only affects really big numbers or numbers with a high precision. For instance, 1.0 / 3.0 == 0.333333333333333314829616256247390992939472198486328125 (Wikipedia[^]). If you are concerned about this, there are macros FLT_EPSILON (for float) and DLB_EPSILON (for double) which define the minimum per

      A Offline
      A Offline
      Alain Rist
      wrote on last edited by
      #12

      Andrew Brock wrote:

      double RoundToOneTenth(double nNumber)
      {
      return floor(nNumber * 10.0 + 0.5) * 0.1;
      }

      This is the solution I would recommend. Note that I changed /10 to *0.1.

      -5.51 => -5.4 :laugh: cheers, AR

      When the wise (person) points at the moon the fool looks at the finger (Chinese proverb)

      N 1 Reply Last reply
      0
      • A Andrew Brock

        While this works, converting to a string, and then back to a float is a slow way of doing it. Check my other answer for alternatives that work.

        A Offline
        A Offline
        Alain Rist
        wrote on last edited by
        #13

        Hi Andrew, 1 With a modern compiler implementing move semantics it is not that slow. You can also quicken it with a template for decimal. 2 It is safe, accurate and handles negative values. 3 It is flexible. You don't have to write a new one for each rounding you may need. All in all this is an academic discussion :) Real world uses fixed point representations when needing rounded decimal values. cheers, AR

        When the wise (person) points at the moon the fool looks at the finger (Chinese proverb)

        1 Reply Last reply
        0
        • A Alain Rist

          Andrew Brock wrote:

          double RoundToOneTenth(double nNumber)
          {
          return floor(nNumber * 10.0 + 0.5) * 0.1;
          }

          This is the solution I would recommend. Note that I changed /10 to *0.1.

          -5.51 => -5.4 :laugh: cheers, AR

          When the wise (person) points at the moon the fool looks at the finger (Chinese proverb)

          N Offline
          N Offline
          Niklas L
          wrote on last edited by
          #14

          Alain Rist wrote:

          -5.51 => -5.4

          Not so bad, since we're talking round numbers. :-D

          home

          1 Reply Last reply
          0
          • A Amrit Agr

            Hello I want to gt only one digit after point so that I can get proper result from calculation like 128 * (1/1.3) instead of 128* (1/1.333333).

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #15

            See also my answer to your previous question.

            I must get a clever new signature for 2011.

            1 Reply Last reply
            0
            • A Andrew Brock

              Some of the suggested answers are ok, but are lacking correct rounding.

              Luc Pattyn wrote:

              double roundToOneTenth(double number) {
              return 0.1*(int)(10.*number);
              }

              Should be:

              double RoundToOneTenth(double nNumber) {
              return (int)(10.0 * nNumber + 0.5) * 0.1;
              }

              While this solution works, it requires converting a floating point number to an integer and back to a floating point number. This is somewhat slow.

              Hans Dietrich wrote:

              double d = floor(1.333333 * 10.) / 10.;

              Should be:

              double RoundToOneTenth(double nNumber) {
              return floor(nNumber * 10.0 + 0.5) * 0.1;
              }

              This is the solution I would recommend. Note that I changed /10 to *0.1. It is faster to multiply than to divide. In a simple case like this the compiler would make this change for you but I am just pointing this out.

              Alain Rist wrote:

              #include <sstream>
              #include <iomanip>
              double Round(double val, size_t decimal)
              {
              std::ostringstream oss;
              oss << std::fixed << std::setprecision(decimal) << val << std::ends;
              std::istringstream(oss.str()) >> val;
              return val;
              }

              While this works and saves you from worrying about rounding errors, this is incredibly slow and uses much more memory (although still not much) than other solutions. There is no need for using strings for such a simple operation. Having said that, it is good that people are posting alternatives to show just how many ways there are for doing this.

              Cedric Moonen wrote:

              Are you aware that floating points number have a rounding error ? You'll never be able to represent perfectly a float in memory.

              While this is absolutely true, it only affects really big numbers or numbers with a high precision. For instance, 1.0 / 3.0 == 0.333333333333333314829616256247390992939472198486328125 (Wikipedia[^]). If you are concerned about this, there are macros FLT_EPSILON (for float) and DLB_EPSILON (for double) which define the minimum per

              R Offline
              R Offline
              Rick York
              wrote on last edited by
              #16

              That rounding calculation fails with negative numbers. This will work with positives, negatives, and zero :

              int RoundValue( double value )
              {
              int result = 0;
              if( value < 0 )
              result = (int)( value - 0.5 );
              else
              result = (int)( value + 0.5 );
              return result;
              }

              Also - yes, it is faster to mulitply than to divide but the percentage of difference is very small (around 10% in my tests) so that is not enough that I would worry about it. Actually, since it is so close I would refrain from changing to multiplies because occasionally it can result in a loss of clarity and the compiler will do it for us when it can.

              modified on Wednesday, February 23, 2011 2:02 PM

              A S 2 Replies Last reply
              0
              • R Rick York

                That rounding calculation fails with negative numbers. This will work with positives, negatives, and zero :

                int RoundValue( double value )
                {
                int result = 0;
                if( value < 0 )
                result = (int)( value - 0.5 );
                else
                result = (int)( value + 0.5 );
                return result;
                }

                Also - yes, it is faster to mulitply than to divide but the percentage of difference is very small (around 10% in my tests) so that is not enough that I would worry about it. Actually, since it is so close I would refrain from changing to multiplies because occasionally it can result in a loss of clarity and the compiler will do it for us when it can.

                modified on Wednesday, February 23, 2011 2:02 PM

                A Offline
                A Offline
                Andrew Brock
                wrote on last edited by
                #17

                Oops, I thought about this for the floor(), but it wasn't the case. Forgot about the casting one. And yes, the percentage is small, but as a game developer any clock cycles I can save by simple things like this are worth it. I guess my views of what is important may differ from others, I prefer high performance over clarity.

                R 1 Reply Last reply
                0
                • R Rick York

                  That rounding calculation fails with negative numbers. This will work with positives, negatives, and zero :

                  int RoundValue( double value )
                  {
                  int result = 0;
                  if( value < 0 )
                  result = (int)( value - 0.5 );
                  else
                  result = (int)( value + 0.5 );
                  return result;
                  }

                  Also - yes, it is faster to mulitply than to divide but the percentage of difference is very small (around 10% in my tests) so that is not enough that I would worry about it. Actually, since it is so close I would refrain from changing to multiplies because occasionally it can result in a loss of clarity and the compiler will do it for us when it can.

                  modified on Wednesday, February 23, 2011 2:02 PM

                  S Offline
                  S Offline
                  Stefan_Lang
                  wrote on last edited by
                  #18

                  You're putting too much value on your solution if you ask me. ;)

                  R 1 Reply Last reply
                  0
                  • S Stefan_Lang

                    You're putting too much value on your solution if you ask me. ;)

                    R Offline
                    R Offline
                    Rick York
                    wrote on last edited by
                    #19

                    thanks for the tip. I hadn't noticed that. ;)

                    1 Reply Last reply
                    0
                    • A Andrew Brock

                      Oops, I thought about this for the floor(), but it wasn't the case. Forgot about the casting one. And yes, the percentage is small, but as a game developer any clock cycles I can save by simple things like this are worth it. I guess my views of what is important may differ from others, I prefer high performance over clarity.

                      R Offline
                      R Offline
                      Rick York
                      wrote on last edited by
                      #20

                      I can understand that - to a point. If you are that concerned with performance there are a lot of other techniques you can use to get big gains in performance. One simple example : if a complex expression or calculation is repeated then save the result in a temporary variable. I have lost count of how many times I have seen people repeat expressions in code. Not only will this have higher performance it will also help maintenance and that is one of my highest priorities. It is been frequently stated that software usually spends more time undergoing maintenance than it does being developed and in my experience this is very true so I believe in making software as maintainable as possible and clarity is very important for this. One more thing - as you said before, the compiler will convert to multiplies automatically when it can so, to me, it makes no sense to sacrifice clarity for something that is done for you transparently. In fact, I find it completely ridiculous but opinions vary.

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups