How can i print the numbers of a float/double variable after the decimal point?
For example for 435.5644
it will output 5644
.
Asked
Active
Viewed 4,768 times
1

abatishchev
- 98,240
- 88
- 296
- 433

user1014842
- 11
- 1
- 3
3 Answers
4
try with
fraction = value - (long) value;
or :
fraction = value - Math.Floor(value);

Spudley
- 166,037
- 39
- 233
- 307

Aghilas Yakoub
- 28,516
- 5
- 46
- 51
-
Better than the solution I was in the middle of typing! – Liam Jul 31 '12 at 15:51
-
I'am happy to help you Liam and user1014842 – Aghilas Yakoub Jul 31 '12 at 15:52
-
this are not only the parts after the decimal point. fraction is btw 0.56439999999997781. Think that is not what OP wants. – Mare Infinitus Jul 31 '12 at 15:56
-
Go with the second option, converting to `long` may have overflow issues with certain numbers (albiet very large numbers). – Matthew Jul 31 '12 at 16:01
-
The double representation problems are not solved there either. see my comment above on the result of the calculation (fraction) – Mare Infinitus Jul 31 '12 at 16:12
1
You can try the following:
double d = 435.5644;
int n = (int)d;
var v = d - n;
string s = string.Format("{0:#.0000}", v);
var result = s.Substring(1);
result: 5644

Mare Infinitus
- 8,024
- 8
- 64
- 113
-1
EDIT: reference to another question (http://stackoverflow.com/questions/4512306/get-decimal-part-of-a-number-in-javascript) You can do the following:
double d = 435.5644;
float f = 435.5644f;
Console.WriteLine(Math.Round(d % 1, 4) * 10000);
Console.WriteLine(Math.Round(f % 1, 4) * 10000);
That will give you the integer part you looking for.
Best is to do it as Aghilas Yakoub answered, however, here below another option using string handling. Assuming all amounts will have decimals and that decimal separator is a dot (.) you just need to get the index 1.
double d = 435.5644;
Console.WriteLine(d.ToString().Split('.')[1]);
float f = 435.5644f;
Console.WriteLine(f.ToString().Split('.')[1]);
Otherwise you may get a Unhandled Exception: System.IndexOutOfRangeException.

Carlos Quintanilla
- 12,937
- 3
- 22
- 25
-
Nice idea, but as you stated will have some problems when integers are passed in – Mare Infinitus Jul 31 '12 at 16:14