turning 1.234 to 1234

hi,i need to turn a float number to integer with deleting its point sign.
like this: 1.234 turns to 1234.
i'm in need of your help for the condition that i should write in the while structure.

float n ;
cin >> n ;
while( ???? )
{
n*=10 ;
}
cout << n ;
Last edited on
Why don't you convert your float to a string, remove the point sign and convert it to an int?
Well, the float number 1.234 is actually (probably) 1.2339999675750732421875

http://floating-point-gui.de/

https://www.h-schmidt.net/FloatConverter/IEEE754.html

So you're basically asking to multiply it by ten many times, and then rounding down to an int. How do you intend to know how many times you're going to multiply by ten? Or will it ALWAYS be 10x10x10 (i.e. a thousand)?




Repeaters point is important, especially as your loop multiplies by ten. This will change the fraction part which will almost definitely change the digits in the fraction part. your resulting value will most likely be a hodge podge of digits and not represent the original very well.

floats aren't very good at storing accurate values, and when you multiply them you are magnifying that difference.

I'd go with Thomas, it will avoid all of the rounding errors you could encounter within your loop.

i tried it here...
http://cpp.sh/9w6h4

1.2345 worked but 1.23456 did not.

1.2345 results
1
2
3
4
5
6
7
8
9
10
1.2345
processing because diff is 0.2345
n is 12.345
processing because diff is 0.345
n is 123.45
processing because diff is 0.450005
n is 1234.5
processing because diff is 0.5
n is 12345
result is 12345


1.23456 results
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1.23456
processing because diff is 0.23456
n is 12.3456
processing because diff is 0.3456
n is 123.456
processing because diff is 0.456001
n is 1234.56
processing because diff is 0.560059
n is 12345.6
processing because diff is 0.600586
n is 123456
processing because diff is 0.0078125
n is 1.23456e+06
processing because diff is 0.125
n is 1.23456e+07
result is 1.23456e+07
Thank you all for your answers. i used all of your advises to put them together for finding the best way.
Topic archived. No new replies allowed.