ToString的默认数字格式

时间:2014-02-26 12:33:28

标签: c# .net cultureinfo number-formatting

是否可以定义在将integer(或double等)转换为String而未指定格式字符串时使用的默认数字格式?

C#示例:

int i = 123456;

string s = "Hello " + i;
// or alternatively with string.Format without format definition
string s = string.Format("Hello {0}", i);

ASP.NET Razor示例:

<div>
    Hello @i
</div>

我认为所有这些代码行都隐式使用ToString()的默认Int32方法。毫不奇怪,所有这些代码行都会产生"Hello 123456",但我想要"Hello 123,456"

我可以指定默认情况下应使用"N0"(至少integer)吗?

我已经找到问题Set Default DateTime Format c# - 它看起来不错,但它对数字没有帮助。


编辑: 我知道我可以编写一个扩展方法,我可以在整个应用程序中使用它,但这不是我想要的。我想找到一个属性(可能隐藏在CultureInfoNumberFormatInfo中的某个位置),该属性当前设置为"G",并由默认的Int32.ToString()实现使用。

5 个答案:

答案 0 :(得分:0)

您可以将系统toString()方法覆盖到您的类中,如下所示:

 public override string ToString()
    {
    int i = 123456;
        string s = "Hello " + i;
      return string.Format("Hello {0}", i);
    }

答案 1 :(得分:0)

您可以使用扩展方法

public static class MyExtensions
{
    public static string ToDefaultFormatString(this int i)
    {
        //Staf
    }
}

,您的代码看起来像

int i = 123456;

string s = "Hello " + i.ToDefaultFormatString();

答案 2 :(得分:0)

当您尝试修改没有类的基本类型的功能时,您无法覆盖ToString()方法。

但您可以创建扩展方法。

namespace System
{

    public class IntExt
    {
        public string ToStringN0(this int i)
        {
            return i.ToString("N0");
        }
    }

}

然后使用

int i = 5000;
Console.WriteLine(i.ToStringN0());

该示例将该类放在System命名空间中,以便它可以通过应用程序使用。

答案 3 :(得分:0)

如果您创建自己的$(document).ready(() => { const mapEl = $('#our_map').get(0); // OR document.getElementById('our_map'); // Display a map on the page const map = new google.maps.Map(mapEl, { mapTypeId: 'roadmap' }); const buildings = [ { title: 'London Eye, London', coordinates: [51.503454, -0.119562], info: 'carousel' }, { title: 'Palace of Westminster, London', coordinates: [51.499633, -0.124755], info: 'palace' } ]; placeBuildingsOnMap(buildings, map); }); const placeBuildingsOnMap = (buildings, map) => { // Loop through our array of buildings & place each one on the map const bounds = new google.maps.LatLngBounds(); buildings.forEach((building) => { const position = { lat: building.coordinates[0], lng: building.coordinates[1] } // Stretch our bounds to the newly found marker position bounds.extend(position); const marker = new google.maps.Marker({ position: position, map: map, title: building.title }); const infoWindow = new google.maps.InfoWindow(); // Allow each marker to have an info window google.maps.event.addListener(marker, 'click', () => { infoWindow.setContent(building.info); infoWindow.open(map, marker); }) // Automatically center the map fitting all markers on the screen map.fitBounds(bounds); }) }) 并且可以更改它,然后将其分配给CultureInfo,就像在此答案中一样:

https://stackoverflow.com/a/24785761/166921

答案 4 :(得分:-2)