Count the length of a number - c++

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.

Related

Why doesn't this function print all the char array as it takes it?

i was trying to convert from a char array to integers and the atoi function is working properly except when i put a zero in the first index...it didn't print it
#include<iostream>
using namespace std;
int main()
{
char arr[]= "0150234";
int num;
num=atoi(arr);
cout << num;
return 0;
}
I expect the output of 0150234 but the actual output is 150234
I think inside the atoi function you have typecasted the string to integer because of which the 0 gets removed. You can never get a 0 printed before a number since it doesn't make sense.
000001 will always be represented as 1.
I hope this clears your doubt.
Binary number representations (such as int) do not store leading 0s because there is an infinite number of them. Rather they store a fixed number of bits which may have some leading 0 bits.
You can still print the leading 0s if necessary:
std::cout << std::setw(4) << std::setfill('0') << 1 << '\n';
Output:
0001
You're confusing two ideas:
Numbers: These are abstract things. They're quantities. Your computer stores the number in a manner that you should not care about (though it's probably binary).
Representations: These are ways we display numbers to humans, like "150234", or "0x24ADA", or "one hundred and fifty thousand, two hundred and thirty four". You pick a representation when you convert to a string. When streaming to std::cout a representation is picked for you by default, but you can choose your own representation using I/O manipulators, as Maxim shows.
The variable num is a number, not a representation of a number. It does not contain the information «display this as "0150234"». That's what arr provides, because it is a string, containing a representation of a number. So, if that leading zero in the original representation is important to you, when you print num, you have to reproduce that representation yourself.
By the way…
Usually, in the programming world, and particularly in C-like source code:
When we see a string like "150234" we assume that it is the decimal (base-10) representation of a number;
When we see a string like "0x24ADA" (with a leading 0x) we assume that it is the hexadecimal (base-16) representation of a number;
When we see a string like "0150234" (with a leading 0) we assume that it is the octal (base-8) representation of a number.
So, if you do add a leading zero, you may confuse your users.
FYI the conventional base-8 representation of your number is "0445332".

How to calculate number of digits before and after decimal point? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Today a question was asked in my c++ class test. "Write a program that inputs a floating point number and calculates the number of digits before and after decimal point."
I calculated numbers before decimal points with this code:
float n;
cin>>n;
float temp = n;
int count = 0;
while(temp1 > 1) {
count++;
temp = temp/10;
}
cout<<count;
but I stuck with after part. Can anyone tell me how to do this? or can provide the whole program?
Thanks in advance,
Write a program that inputs a floating point number and calculates the number of digits before and after decimal point.
Well, as is that task is asking for something not really solvable using a float and standard c++, because the binary representation of a float values exponent and mantissa isn't defined in the c++ standard.
Hence you can't know how many digits will be used to represent the fraction part of the number, unless you know how exactly the c++ compiler implemented float (or double) binary representations.
Most probably the implementation is optimized for the target CPU and its capabilities how to deal with floating point values.
So the only chance you have is to read the number as a std::string representation in 1st place, count the digits that appear before and after the '.' character, and finally convert the std::string variable to a float value.
Here's a simple illustration what I meant in the 1st part of my answer:
#include <iostream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <sstream>
int main() {
std::istringstream iss("3.1415"); // same as reading from cin
std::cout << "Input: " << iss.str() << std::endl;
float temp;
iss >> temp;
std::cout << "Internal representation: "
<< std::fixed << std::setprecision(22) << temp << std::endl;
float fraction = temp - abs(temp);
int fractiondigits = 0;
while(fraction > std::numeric_limits<float>::epsilon()) { // epsilon is the smallest
// value that can be
// represented in binary form
fraction *= 10.0f;
fraction -= abs(fraction);
++fractiondigits;
}
std::cout << "Number of digits used in the representation: "
<< fractiondigits << std::endl;
}
The output is
Input: 3.1415
Internal representation: 3.1414999961853027343750
Number of fraction digits used in the representation: 21
Live Demo
So you see that's not congruent with the user's input.
I don't know if your professors intend was to ask about and letting you acknowledge this incongruence of user input and internal representation of float.
But as mentioned the actual count of digits is compiler implementation and platform dependent, so there's no definite answer for the number of fraction digits.
The question is fundamentally irrelevant. Most real numbers have infinitely many digits, but computer represented numbers must have a finite representation. For the common case of a binary representation, the represented number also has a finite decimal representation. However, truncating this decimal representation at fewer digits (as few as std::numeric_limits<float>::max_digits10 to be precise) still obtains the same representable number. Thus, the relevant number of digits for computer floating-point numbers best refers to their binary rather than their decimal representation. This is given by std::numeric_limits<float>::digits (total: in front of and after the point).

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).

stringstream setprecision and floating point formatting

double value = 02369.000133699;//acutally stored as 2369.000133698999900
const std::uint32_t left = std::uint32_t(std::abs(value) < 1 ? 1: (1 + std::log10(std::abs(value))));
std::ostringstream out;
out << std::setprecision(std::numeric_limits<T>::digits10 - left ) << std::fixed << value;
std::string str = out.str(); //str = "2369.00013369900"
std::ostringstream out2;
out2 << std::setprecision(std::numeric_limits<T>::digits10 ) << std::fixed << value;
std::string str2 = out2.str(); // str2 = "2369.000133698999900"
I'm wondering how std::stringstream/precision works for formatting floating-point number.
It seems that if precision argument is superior to 16 minus number of non-fractional digits, this lead to a formatting of form "2369.000133698999900" instead of a "nice" "2369.00013369900"
how std::stringstream know that 8999900 must be resume to one 9 even if I don"t tell it to do the rounding on the 8 (like passing 12 as argument to the setprecision function) ?but don't do it for argument superior to 12
Formatting binary floating points as decimal values is fairly tricky. The underlying problem is that binary floating points cannot represent decimal values accurately. Even a simple number like 0.1 cannot be represented exactly using binary floating points. That is, the actual value represented is slightly different. When using clever algorithms for reading ("Bellerophon") and formatting ("Dragon4"; these are the names from the original papers and there are improvements of both algorithms which are used in practice) floating point numbers be used to transport decimal values. However, when asking the algorithm to format more decimal digits than it can actually hold, i.e., more than std::numeric_limits<T>::digits10, it will happily do so, [partially] revealing the value it is actually storing.
The formatting algorithm ("Dragon4") assumes that the value it is given is the value closest to the original representable with the floating point type. It uses this information together with an error estimate for the current position to determine the correct digits. The algorithm itself is non-trivial and I haven't fully understood how it works. It is described in the paper "How to Print Floating-Point Numbers Accurately" by Guy L. Steele Jr. and Jon L. White.

C++ count the number of digits of a double

i want to do what the title says like this:
int number1;
cin>>number1;
num1len=log10(number1)+1;
cout<<"num of digits is "<<num1len<<"\n";
but when the number of digits is 11 and more the answer is always 7(6+1)
Does anyone knows why or what im i doing wrong?
Floating-point data types, including double, store approximations. What you're finding by calling log10 is the number of places to the left of the decimal point, which is affected by at most one by the approximation process.
The question you asked, how to find the number of decimal digits in a number stored in binary floating-point, is meaningless. The number 7.1 has two decimal digits, however its approximate floating-point representation doesn't use decimal digits at all. To preserve the number of decimal digits, you'd need some decimal representation, not the C++ double data type.
Of course, all of this is applicable only to double, per the question title. Your code snippet doesn't actually use double.
What is 'wrong' is the maximum value which can be stored in a (signed) int :
#include <iostream>
#include <numeric>
int main()
{
std::cout << std::numeric_limits<int>::max() << std::endl;
}
Gives me :
2147483647
You are running past the unsigned 32-bit boundary ... your number of 11 digits or more exceeds 0xFFFFFFFF, and so wraps around.
You need to use either unsigned long long or double for your number1 variable:
#include <iostream>
#include <cstdlib>
#include <cmath>
int
main ( int argc, char * argv[] )
{
unsigned long long num; // or double, but note comments below
std::cin >> num;
std::cout << "Number of digits in " << num << " is " << ( (int) std::log10 ( num ) + 1 ) << std::endl;
return 0;
}
Those large numbers will print in scientific notation by default when you send them to std::cout if you choose to use double as your data type, so you would want to throw some formatting in there. If you use an unsigned long long instead, they will print as they were entered, but you have to be sure that your platform supports unsigned long long.
EDIT: As mentioned by others, use of floating point values has other implications to consider, and is most likely not what you are ultimately trying to achieve. AFAIK, the integral type on a platform that yields the largest positive value is unsigned long long, so depending on the values you are looking to work with, see if that is available to you for use.
Others have pointed out that floating point numbers are approximations, so you can't really get an accurate count of digits in it.
But...you can get something approximate, by writing it out to a std::stringstream object, then converting it to a std::string, and getting the lenght of the said string. You'll of course have to deal with the fact that there may be non-digit characters in the string (like minus sign, decimal point, E for exponent etc). Also the number of digits you obtain in this manner would be dependent on formatting options you choose when writing to the stringstream object. But assuming that you know what formatting options you'd like to use, you can get the number of digits subject to these options.