leora
leora

Reputation: 196689

Whats the best way to format this number?

I have a double and I want to format it with the following rules:

  1. If there are no decimal places show just the number (see 100 example below)
  2. If there are any decimal places show 2 decimal places

So, as a few examples:

100 --> 100  
99.958443534 --> 99.96  
99.1 -> 99.10  

Upvotes: 3

Views: 176

Answers (3)

WaltiD
WaltiD

Reputation: 1952

What about:

var a = 100;
var b = 99.95844354;

var aAnswer = a.ToString("0.##"); //aAnswer is "100"
var bAnswer = b.ToString("0.##"); //bAnswer is "99.96"

Upvotes: 1

SwDevMan81
SwDevMan81

Reputation: 50018

You could check if its a whole number, the use the type of formatting based on that:

string res = string.Format(((number % 1) == 0) ? "{0:0}" : "{0:0.00}", number);

Upvotes: 4

Neil Knight
Neil Knight

Reputation: 48567

You can use:

decimal a = 99.949999999M;

Math.Round(a, 2);  // Returns 99.95

Upvotes: 0

Related Questions