簡體   English   中英

使用逗號格式化十進制,保留尾隨零

[英]Format decimal with commas, preserve trailing zeros

我想將小數轉換為字符串,逗號為數千個分隔符,並保留創建小數的相同精度。 (將有2-5位有關數字)

        decimal d = 1234.4500M;

        //I'd like "1,234.4500"

        var notRight = d.ToString("###,###.#######");     //1,234.45
        var alsoNotRight = d.ToString("###,###.00000");;  //1,234.45000
        var notRightEither = d.ToString("N");    //1,234.45
        var notRightEither2 = d.ToString("G");   //1234.45000

如果不手動解析字符串,是否沒有內置方法可以做到這一點? 如果沒有單一格式字符串,最簡單的方法是什么?

根據文檔 ,十進制數保留尾隨零。 如果使用“G”說明符或根本沒有說明符,則可以顯示它們。 當您使用包含千位分隔符的說明符之一時,它們會丟失。

如果要在轉換為字符串時指定尾隨零的數量,可以通過在格式字符后添加精度說明符 (0到99位)來完成,如下所示:

decimal d=1234.45M;
var numberAsString=d.ToString("N4");

結果將是

 1,234.4500

更新:您可以使用Decimal.GetBits方法獲取小數位數,該方法返回數字的二進制表示形式。 小數位數存儲在第四個元素的位16-23(第三個字節)中。

The fourth element of the returned array contains the scale factor and sign. It consists of the following parts:

...

Bits 16 to 23 must contain an exponent between 0 and 28, which indicates the power of 10 to divide the integer number.

使用所有數字獲取字符串表示可以這樣做:

decimal d=1234.45000M;
var nums=Decimal.GetBits(d);
var decimals=BitConverter.GetBytes(nums[3])[2];
var formatStr="N"+decimals;
d.ToString(formatStr);

這將產生

1,234.45000

由於您計划使用可變數量的小數位(2-5) ,我認為您不能通過字符串格式將其拉出。

這個解決方案並不是必需的,但它可以完成工作。 請注意,它將在過程中分配幾個字符串(我相信5),因此在大規模使用中可能效果不佳。 您將保留小數位數,並在小數點前的部分中獲取逗號分隔的組。

public static string FormatDecimal(decimal d)
{
    return d.ToString("N0") + // Format portion before decimal
           "." + 
           d.ToString().Split('.')[1];  // Retain number of decimal places
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM