Updated Answer
Here I give three approaches for the same.
[1] Mathematical 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.1999999999999992929
If this is not the result you expect, then you need to change the result to the form you want (but you can do some string manipulation again.)
[2] using the factor [which is 10 to the power N (for example, 10² or 10³), where N is the number of decimal places]
// multiplier is " 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 can create problems.
[3] using "Regular Expressions (REGEX)"
We must be very careful when writing solutions with a string. This one is not preferable , except in some cases.
If you intend to perform some decimal operations , 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 at http://www.regexr.com/
Karthik Krishna Baiju Oct. 15 '13 at 6:14 2013-10-15 06:14
source share