开发者

Whats the best way to format this number?

开发者 https://www.devze.com 2023-04-02 14:59 出处:网络
I have a double and I want to format it with the following rules: If there are no decimal places show just the number(see 100 example below)

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 de开发者_如何学Gocimal places

So, as a few examples:

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


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


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"


You can use:

decimal a = 99.949999999M;

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

精彩评论

暂无评论...
验证码 换一张
取 消