user1095549 - 9 months ago 81

C# Question

I want to receive the number after the decimal dot in the form of an integer. For example, only 05 from 1.05 or from 2.50 only 50 **not** 0.50

Answer Source

Here I am giving 3 approaches for the same.

**[1] using "Regular Expressions (REGEX)"**

// If you are going to do some string operations with decimal places, then this would be preferable

```
string input_decimal_number = "1.50";
var regex = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
if (regex.IsMatch(input_decimal_number))
{
string decimal_places = regex.Match(input_decimal_number).Value;
}
```

// input : "1.05"

// output : "05"

// input : "2.50"

// output : "50"

// input : "0.0550"

// output : "0550"

you can find more about Regex on http://www.regexr.com/

**[2] Math Solution using Math.Truncate**

```
var float_number = 12.345;
var result = float_number - Math.Truncate(float_number);
```

// input : 1.05

// output : "0.050000000000000044"

// input : 10.2

// output : 0.19999999999999929

If this is not the result what you are expecting, then you have to change the result to the form which you want (but you might do some string manipulations again.)

**[3] using multiplier [which is 10 to the power of N (e.g. 10² or 10³) where N is the number of decimal places]**

```
// this should be 10 to the power of 'n' where 'n' is the number
// of decimal places
int multiplier = 1000; double double_value = 12.345;
int double_result = (int)((double_value - (int)double_value) * multiplier);
```

// output 345

If the number of decimal places is not fixed, then this approach may create problems.