I am trying to remove just the decimal point from a decimal number in C#.
For example:
2353.61
I want 235361
as the result.196.06
I want 19606
as the result.How can I do that?
To remove the decimal point we have to convert it into a rational number. To convert a decimal to a rational number follow these steps: Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point.
Type conversion in python helps to convert a decimal value number(floating number) to an integer. Thus converting float->int removes all decimals from a number.
Answer: 0.2 when converted into a fraction is 1/5. Then, this fraction can be simplified. In this case, 0.2 has one number after the decimal, so, we place 10 in the denominator and remove the decimal point.
I would simply get the number of decimals and multiply it by the correct power of 10. Probably not really a concern but this also would be faster and use less memory then casting it to a string splitting / recombining it, then casting it back to a double. This also works for any number of decimal places.
decimal d = 2353.61M;
int count = BitConverter.GetBytes(decimal.GetBits(d)[3])[2];
d *= Convert.ToDecimal(Math.Pow(10, count));
Using this answer to get the number of decimals.
If you always want the printed value to include 2 digits for consistency, you can just multiple by 100 and truncate the result.
value = Math.Truncate(value * 100m);
This would provide the value you specified in both cases, but also provide a similar result for 2353.6
(-> 235360
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With