Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying numbers without decimal points

Tags:

c#

I want to display a number in a report, however I only want to show any decimal points if they are present and the I only want to show 1 decimal space.

e.g. if the number is 12 then I want to show 12

If the number is 12.1 then I want to show 12.1

If the number is 12.11 then I want to show 12.1

like image 269
user226305 Avatar asked Dec 07 '09 11:12

user226305


People also ask

What is a number without a decimal called?

Integers. Integers whole numbers that can be positive, negative or zero, but have no decimal places or fractional parts.

How do you get rid of decimal points?

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. (For example, if there are two numbers after the decimal point, then use 100, if there are three then use 1000, etc.) Step 3: Simplify (or reduce) the Rational number.


2 Answers

I had a very similar problem a while ago and the answer is to use a format string when converting the number to a string. The way to solve your issue is to use a custom numeric format string of "0.#"

double x = 12;
double y = 12.1;
double z = 12.11;
Console.WriteLine(x.ToString("0.#"));
Console.WriteLine(y.ToString("0.#"));
Console.WriteLine(z.ToString("0.#"));

Will give you the following output:

12

12.1

12.1

like image 102
John Nunn Avatar answered Oct 20 '22 07:10

John Nunn


This will return a number with a single (optional) decimal place.

String.Format("{0:0.#}", number)
like image 23
Richard Avatar answered Oct 20 '22 08:10

Richard