Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove decimal point from a decimal number

Tags:

c#

decimal

I am trying to remove just the decimal point from a decimal number in C#.

For example:

  • My decimal number is 2353.61 I want 235361 as the result.
  • My decimal number is 196.06 I want 19606 as the result.

How can I do that?

like image 447
user3661657 Avatar asked Jul 21 '14 18:07

user3661657


People also ask

How do you remove a point from a decimal number?

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.

How do I remove a decimal point from a number in Python?

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.

How do you get rid of 0.2 As a decimal?

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.


2 Answers

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.

like image 137
ClassicThunder Avatar answered Sep 22 '22 10:09

ClassicThunder


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).

like image 35
Reed Copsey Avatar answered Sep 21 '22 10:09

Reed Copsey