Snerd
Snerd

Reputation: 1553

decimal formatting with more elegance C++

I have this code:

            void FeetInches::decimal() 
            {
                if (inches == 6.0)
                {
                    inches = 5;
                    std::cout << feet << "." << inches << " feet";  //not the best but works..
                }
            }

This will print something like 12 feet 6 inches as 12.5 feet. I would prefer to not use this "hackish" method and make it like this:

            void FeetInches::decimal() 
            {
                if (inches == 6.0)
                {
                    inches = .5;
                    std::cout << feet << inches << " feet";  //not the best but works..
                }
            }

But this will print 60.5 inches (I need 6.5 inches). Basically if I print inches alone it prints 0.5. I want inches to print only .5 without the zero. Cant a printf method or another quick technique implement this? The data types are double by the way

Upvotes: 1

Views: 147

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83527

How about converting your inches to feet first:

feet = feet + inches / 12.0;

Now print out the result. Or if you don't want to change your feet variable, either do the calculation directly in your cout statement or use a temporary variable for the calculation.

Upvotes: 8

Related Questions