开发者

How to make sure a zero is always at the end

开发者 https://www.devze.com 2023-02-21 18:25 出处:网络
I need t开发者_开发问答o make sure that a double always ends with 0 6 = 6.0 5.9876577878 = 5.98765778780

I need t开发者_开发问答o make sure that a double always ends with 0

6 = 6.0  
5.9876577878 = 5.98765778780

I tried the format but did not bring the expected result.

How can this be done?


Not sure if the String.Format method allows you to do this. Here's something you can do though:

public static class DoubleUtils {
    public static String EnsureEndsWithZero(this double value) {
        String str = value.ToString();
        if(!str.EndsWith("0")) {
            if(str.Contains(".")) {
                str += "0";
            } else {
                str += ".0";
            }
        }
        return str;
    }
}

Usage:

double val = 10.1;
Console.WriteLine(val.EnsureEndsWithZero());


Unless you're extremely liberal about how many zeros are at the end of the number (i.e. 1 OR MORE zeros is okay), then I think you'd have to check the resulting string to see if there's a zero after the decimal point, and add one or both if they aren't there.

0

精彩评论

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