0

I need to somehow get one number before floating point and value after that floating point. Example:

Before: 212.12345;
After: 2.12345

Any Ideas?

user2086174
  • 195
  • 1
  • 3
  • 12
  • I do not know the C# API, but how about converting the number to a String, then create a substring with the needed numbers and parse it to a double again? – Mirco Jul 31 '13 at 06:38
  • you can convert it to string and than use substring method combined by indexOf method. – Habibillah Jul 31 '13 at 06:39

5 Answers5

8

Assuming you have:

decimal x = 212.12345m;

you can use the modulo operator:

decimal result = x % 10;

Note that the number should be represented as a decimal if you care about the accurate value.

See also: Meaning of "%" operation in C# for the numeric type double

Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • 4
    Although if the exact decimal digits are important, the OP should consider using `decimal` rather than `double`. – Jon Skeet Jul 31 '13 at 06:43
  • @JonSkeet - Good point! the question mentions floating point, I'm not sure what that means for the OP. Either way, `%` should work. – Kobi Jul 31 '13 at 06:46
  • He is removing two digits 12 before decimal point as 212.12345 need to be 2.12345, How modulus operator would do that? – Adil Jul 31 '13 at 06:51
  • @Adil - The assumption here is `1234.5` -> `4.5`, not `1.5`. This is marked by the OP using bold text: "21 **2.12345**", though I agree the question is very poorly written. – Kobi Jul 31 '13 at 06:53
  • I misunderstood that. – Adil Jul 31 '13 at 06:55
  • He needs to write a parser to chop off the numbers 2 places before the ".". – ZeroPhase Jul 31 '13 at 07:00
  • @ZeroPhase - Isn't that another *assumption*? We don't *know* whether the OP has a string or a numeric value. Either way, if the OP is doing an arithmetic operation, they can parse the string - if this is a number, you don't need to parse it. If this is a string, you can easily search for `.` and take a substring. – Kobi Jul 31 '13 at 07:03
0

my approach was to find the number 210, and substract it....
will work for any number as well as smaller then 10.

double f1 = 233.1234;
double f2 = f1 - (((int)f1 / 10) * 10);
Tomer W
  • 3,395
  • 2
  • 29
  • 44
0

try this

double x = 1; 
var y = x/10; 
var z = (y % (Math.Floor(y))) * 10;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Rex
  • 2,130
  • 11
  • 12
0

You can do like this:

public double GetFirst(double a)
{
    double b = a / 10.0;
    return (b - (int)b) * 10.0;
}
0

Try this code

string num = "15464612.12345";
string t = num.Split('.')[0];
num = t[t.Length-1].ToString() + "." + num.Split('.')[1];
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Sandip
  • 372
  • 1
  • 7
  • wont work in many situations like: `num = 123845` or `regional settings set numbers to exponent representation 1.546461212345e7` or alternativly `regional use comma instead of dot like 15464612,12345` – Tomer W Jul 31 '13 at 13:28