C# - 字符串格式:双固定宽度 [英] C# - String formatting: double fixed width

查看:302
本文介绍了C# - 字符串格式:双固定宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#中使用 String.Format ,所以双打显示如下:

How can I use String.Format in C# so doubles are displayed like this:

值: / p>

Values:

-1.0
1.011
100.155
1000.25
11000.52221

显示字符串:

-1.00
1.011
100.2
 1000
11001

主要是我的宽度固定为5个字符,无论什么。我真的不在乎右边显示了几个小数位。如果小数点左边有4个或更多的数字,我希望删除十进制的所有权利(包括小数本身)。

The main point is my width is fixed to 5 characters no matter what. I don't really care how many decimal places are shown to the right. If there are 4 or more numbers to the left of decimal I want everything right of the decimal to be dropped (including the decimal itself).

看起来应该是是一个很标准的做法。但是我没有多少运气找到一个有效的答案。

It seems like something that should be a pretty standard practice. But I'm not having much luck finding an answer that works.

对上面的显示字符串进行了几次更正,我想要舍入。 / strong>

A couple of corrections were made to the display string above, I do want rounding.

谢谢!

推荐答案

public string FormatNumber(double number)
{
    string stringRepresentation = number.ToString();

    if (stringRepresentation.Length > 5)
        stringRepresentation = stringRepresentation.Substring(0, 5);

    if (stringRepresentation.Length == 5 && stringRepresentation.EndsWith("."))
        stringRepresentation = stringRepresentation.Substring(0, 4);

    return stringRepresentation.PadLeft(5);
}

编辑:只是意识到这不会在零末如果需要,你可以使用十进制(如你的第一个例子),但是应该给你工具来完成你的需要。

Just realized that this doesn't pad zeros at the end of the decimal if necessary (as in your first example) but should give you the tools to finish it off as you need to.

EDITx2:给你最近的补充,你打算有四舍五入,变得越来越复杂。首先,你必须做一个检查才能看到,如果你将有任何小数位和十进位的位置。那么你必须将其舍入到小数位,然后可能会运行输出。请注意,根据您的算法,您可能会收到一些不正确的结果,其中舍入滚动数字(例如, -10.9999 可能会变为 -11.00 -11 取决于您的实现)

EDITx2: Given your most recent addition that you intend to have rounding, it gets more complicated. First you have to do a check to see if you will have any decimal places and at what position the decimal is. Then you have to round it to that decimal place, then probably run through the output. Note that depending on your algorithm, you could get some incorrect results where rounding rolls over numbers (for example, -10.9999 could become -11.00 or -11 depending on your implementation)

这篇关于C# - 字符串格式:双固定宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆