Convert a double to fixed decimal point in C++ - c++

I have a double variable in C++ and want to print it out to the screen as a fixed decimal point number.
Basically I want to know how to write a function that takes a double and a number of decimal places and prints out the number to that number of decimal places, zero padding if necessary.
For example:
convert(1.235, 2)
would print out
1.24
and
convert(1, 3)
would print out
1.000
so the function works as
convert(number as double, number of decimal places)
and simply prints out the required value to standard output (cout).
Does anyone know how to do this?
Thanks in advance.

Assuming I'm remembering my format strings correctly,
printf("%.*f", (int)precision, (double)number);

Look at the setprecision manipulator which should give you the idea

There is no such thing as a "fixed decimal place" number. The convert function will need to be the function that actually prints it out. I would suggest getting the whole part of the number, then print it. If [decimal places]>0 then print a decimal place, then print each decimal individually like: floor((n*log(10,d))%10); <-- just an idea, not actual code.

#include <iomanip>
#include <iostream.h>
// print a float, x places of precision
void convert (double number, int x)
{
cout << setprecision(x) << number << endl;
}
int main()
{
double a = 1.234;
convert (a,2);
}
output: 1.23
reference

Related

Count the length of a number

Hello I would like to count the number there is in a number I mean if I have this double 78.23 the functions would return 4 if I have 145.123 I would got 6. Is it possible to do this with C++ ?
Thank you !
Precision - in the sense that you are asking about it - is as much a property of the output stream, as of the value being output. Assuming you are outputting using an C++ ostream (ofstream, ostrstream, etc), look up properties ios_base::precision, ios_base::width, etc or stream manipulator like setprecision. If you are using C I/O (sprintf(), etc), the answer depends upon modifiers specified for the %f format.
So the method to get the value you seek would probably be to output the value using your chosen method (stream manipulators, format specifiers) to a string. Then compute the length of the string, subtract one for every trailing 0, the decimal point, etc.
Also, floating point variables with a base 2 mantissa (which includes most real-world floating point representations) cannot exactly represent any value that is not a sum of integral powers of 0.5 (the stored value is an approximation). Among other things, this means a floating point variable cannot exactly represent values like 0.1 and 0.01. Both of your sample values 78.23 and 145.123 cannot be represented exactly using floating point variables. Which is part of the reason why the answer to questions like yours depends on how the variable is output, as much as the value itself.
the easy way of doing this is to just enter the number as a string and use .length()
#include <iostream>
#include <string>
#include <conio.h>
using namespace std; int main() {
string number;
cout << "Enter a number: ";
cin >> number;
cout << "length is " << number.length();
_getch();
return 0;
if you need it strictly to be with integers and doubles then you'll have to create a mathematical algorithm.

Higher precision when parsing string to float

This is my first post here so sorry if it drags a little.
I'm assisting in some research for my professor, and I'm having some trouble with precision when I'm parsing some numbers that need to be precise to the 12th decimal point. For example, here is a number that I'm parsing from a string into an integer, before it's parsed:
-82.636097527336
Here is the code I'm using to parse it, which I also found on this site (thanks for that!):
std::basic_string<char> str = prelim[i];
std::stringstream s_str( str );
float val;
s_str >> val;
degrees.push_back(val);
Where 'prelim[i]' is just the current number I'm on, and 'degrees' is my new vector that holds all of the numbers after they've been parsed to a float. My issue is that, after it's parsed and stored in 'degrees', I do an 'std::cout' command comparing both values side-by-side, and shows up like this (old value (string) on the left, new value (float) on the right):
-82.6361
Does anyone have any insight into how I could alleviate this issue and make my numbers more precise? I suppose I could go character by character and use a switch case, but I think that there's an easier way to do it with just a few lines of code.
Again, thank you in advance and any pointers would be appreciated!
(Edited for clarity regarding how I was outputting the value)
Change to a double to represent the value more accurately, and use std::setprecision(30) or more to show as much of the internal representation as is available.
Note that the internal storage isn't exact; using an Intel Core i7, I got the following values:
string: -82.636097527336
float: -82.63610076904296875
double: -82.63609752733600544161163270473480224609
So, as you can see, double correctly represents all of the digits of your original input string, but even so, it isn't quite exact, since there are a few extra digits than in your string.
There are two problems:
A 32-bit float does not have enough precision for 14 decimal digits. From a 32-bit float you can get about 7 decimal digits, because it has a 23-bit binary mantissa. A 64-bit float (double) has 52 bits of mantissa, which gives you about 16 decimal digits, just enough.
Printing with cout by default prints six decimal digits.
Here is a little program to illustrate the difference:
#include <iomanip>
#include <iostream>
#include <sstream>
int main(int, const char**)
{
float parsed_float;
double parsed_double;
std::stringstream input("-82.636097527336 -82.636097527336");
input >> parsed_float;
input >> parsed_double;
std::cout << "float printed with default precision: "
<< parsed_float << std::endl;
std::cout << "double printed with default precision: "
<< parsed_double << std::endl;
std::cout << "float printed with 14 digits precision: "
<< std::setprecision(14) << parsed_float << std::endl;
std::cout << "double printed with 14 digits precision: "
<< std::setprecision(14) << parsed_double << std::endl;
return 0;
}
Output:
float printed with default precision: -82.6361
double printed with default precision: -82.6361
float printed with 14 digits precision: -82.636100769043
double printed with 14 digits precision: -82.636097527336
So you need to use a 64-bit float to be able to represent the input, but also remember to print with the desired precision with std::setprecision.
You cannot have precision up to the 12th decimal using a simple float. The intuitive course of action would be to use double or long double... but your are not going to have the precision your need.
The reason is due to the representation of real numbers in memory. You have more information here.
For example. 0.02 is actually stored as 0.01999999...
You should use a dedicated library for arbitrary precision, instead.
Hope this helps.

c++ long double printing all digits with precision

Regarding my question I have seen a post on here but did not understand since i am new to C++. I wrote a small script which gets a number from user and script prints out the factorial of entered number.
Once I entered bigger numbers like 30, script does not print out all the digits.Output is like 2.652528598 E+32 however What I want is exact number 265252859812191058636308480000000. Could someone explain how to get all digits in long double.Thanks in advance
You can set the precision of the output stream to whatever you want in order to get your desired results.
http://www.cplusplus.com/reference/ios/ios_base/precision/
Here is an extract from the page, along with a code example.
Get/Set floating-point decimal precision
The floating-point precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation (either fixed or scientific) or it is unset (using the default notation, which is not necessarily equivalent to either fixed nor scientific).
Using the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum, and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than the precision.
In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case.
This decimal precision can also be modified using the parameterized manipulator setprecision.
// modify precision
#include <iostream> // std::cout, std::ios
int main () {
double f = 3.14159;
std::cout.unsetf ( std::ios::floatfield ); // floatfield not set
std::cout.precision(5);
std::cout << f << '\n';
std::cout.precision(10);
std::cout << f << '\n';
std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
std::cout << f << '\n';
return 0;
}
Possible output:
3.1416
3.14159
3.1415900000
Notice how the first number written is just 5 digits long, while the second is 6, but not more, even though the stream's precision is now 10. That is because precision with the default floatfield only specifies the maximum number of digits to be displayed, but not the minimum.
The third number printed displays 10 digits after the decimal point because the floatfield format flag is in this case set to fixed.

Reading floating point values from a file drops all or part of the decimal part

I need to read floating-point values from a file.
Basic sample code of how I do this:
int main()
{
float number;
ifstream inputFile;
inputFile.open("testfile.dat");
inputFile >> number;
cout << number << endl;
return 0;
}
The first line in the file is: 13212.13131. But when I cout 'number' the displayed number is: 13212.1
The problem is part of the decimal gets dropped and in other cases all of it gets dropped. Why does this happen, and how can I solve this problem?
The point of reading the number from the file is to do mathematical calculations with it.
First, floating-point precision on output (for both std::cout and printf) is 6 decimal digits by default. You need std::setprecision() to get it print more digits. But you'll then get to the limit of float type.
On most systems float is IEEE-754 single precision, therefore it can only store about 7 digits of significant. The nearest to 13212.13131 is 1.3212130859375E4. If you need more precision, you must use double, which has about 15-16 digits of precision on most systems.
Read more: Is floating point math broken?
Try using std::setprecision():
cout << setprecision(14) << number << endl;
You will need to
#include <iomanip>
If that doesn't solve it you should try debugging it and see what the number actually is (13212.13131 or 13212.1).

Double multiplication giving rounded results

double a = 2451550;
double b = .407864;
double c= a*b;
cout<<c;
I was expecting the results to be "999898.9892" but getting "999899". I need the actual unrounded result.Please suggest.
By default, iostreams output 6 digits of precision. If you want more, you have to ask for it:
std::cout.precision(15);
It can also be done using Manipulator setprecision like below.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a = 2451550;
double b = .407864;
double c= a*b;
cout<<setprecision(15)<<c;
}
Also, Usage of manipulator will make the code compact.
By default the precision of an std::iostream will show how many digits total to display and by default precision is 6. So, since your number has six digits before the decimal place it will not display any after the decimal.
You can change this behavior with the 'fixed' manipulator. 'precision' then changes to mean the number of digits to display after the decimal which is probably what you were expecting.
To always get four digits after the decimal you can do this:
cout << setprecision(4) << fixed << c;
However, keep in mind that this will always display four digits after the decimal even if they are zeros. There is no simple way to get 'precision' to mean at most x number of digits after the decimal place with std::iostreams.