+ 1

Hey guys I have a question. How can I split and display ones,tens,hundred,thousand in a number that a user will define.?

For example: if you will enter 3878.69 the output should be thousand display - 3000 five hundred display - 500 next display - 300 next display - 70 next display - 8 and last display - 0.69 how? help please 😊

12th Jul 2017, 9:10 AM
Adrian Jason Rodas
Adrian Jason Rodas - avatar
6 Antworten
+ 1
I believe that's related to the limited precision of the float representation. You can either use double (see my sample code below), or you can round the result to the desired number of decimals (two in your case). #include <iostream> #include <math.h> using namespace std; int main() { double number=3878.69; double decimals=number-trunc(number); cout<< "Decimals = "<<decimals<<" x 100 = "<<decimals*100; return 0; }
13th Jul 2017, 7:35 PM
Bogdan Sass
Bogdan Sass - avatar
+ 2
From right to left, each digit is the remainder of the number divided by 10. So for 3878, the last digit is 3878%10 = 8
12th Jul 2017, 9:39 AM
Bogdan Sass
Bogdan Sass - avatar
+ 2
thanks i fixed it. i just chnged all the float to double.
14th Jul 2017, 12:34 AM
Adrian Jason Rodas
Adrian Jason Rodas - avatar
+ 1
@bogdan sass i dont get it. and what about the decimal?
13th Jul 2017, 4:26 PM
Adrian Jason Rodas
Adrian Jason Rodas - avatar
+ 1
For the decimal, you can just do x-trunc(x)
13th Jul 2017, 4:59 PM
Bogdan Sass
Bogdan Sass - avatar
+ 1
this is my code the they all display the right answer except for the decimal. its output for 3878.69 is 0.689941. I just need it to dipsplay 0.69 but how? is my code wrong? #include <iostream> using namespace std; int main() { float th=0,fvh=0,hnd=0,fty=0,ten=0,one=0,r1=0,r2=0,r3=0,r4=0,r5=0,r6=0,sum=0,mny=0,cnt=0; cout << "How much is your money?:"; cin>>mny; th=(int)mny/1000; cout<< "thousand is = "<<th<<" x 1000 = "<<th*1000; r6=th*1000; r1=(int)mny%1000; cout<< "\nremaining is = "<<(float)r1+cnt; fvh=(int)r1/500; cout<< "\nFive hundred = "<<fvh<<" x 500 = "<<fvh*500; r2=(int)r1%500; cout<< "\nRemaining is = "<<(float)r2+cnt; hnd=(int)r2/100; cout<< "\nHundred = "<<hnd<<" x 100 = "<<hnd*100; r3=(int)r2%100; cout<< "\nRemaining is = "<<(float)r3+cnt; fty=(int)r3/50; cout<< "\nFifty = "<<fty<<" x 50 = "<<fty*50; r4=(int)r3%50; cout<< "\nRemaining is = "<<(float)r4+cnt; ten=(int)r4/10; cout<< "\nTens = "<<ten<<" x 10 = "<<ten*10; r5=(int)r4%10; cout<< "\nRemaining is = "<<(float)r5+cnt; one=(int)r5/1; cout<< "\nOnes = "<<one<<" x 1 = "<<one*1; sum=r1+r6; cnt=mny-sum; cout<< "\nRemaining is = "<<cnt; cout<<"\nCent is = "<<cnt; return 0; }
13th Jul 2017, 5:21 PM
Adrian Jason Rodas
Adrian Jason Rodas - avatar