简体   繁体   中英

Why does it work in LINQPad but not in my code?

I'm trying different format for a price value in an application (ASP.NET MVC 4), first I tested below code in LINQPad and it worked well (no meaningless trailing zeros). But when I put these code, string.Format("G", value) specifically in my code, it didn't work, trailing zeros appear again!!! Why?

LINQPad snippet:

decimal d = 0.3M, d2 = 0.45M, d3 = 13.2M, d4 = 1049M, d5 = 12492.4M, d6 = 2000M;

var culture = CultureInfo.CreateSpecificCulture("vi-VN");

Console.WriteLine(string.Format(culture, "{0:G}", d));
Console.WriteLine(string.Format(culture, "{0:G}", d2));
Console.WriteLine(string.Format(culture, "{0:G}", d3));
Console.WriteLine(string.Format(culture, "{0:G}", d4));
Console.WriteLine(string.Format(culture, "{0:G}", d5));
Console.WriteLine(string.Format(culture, "{0:G}", d6));

LINQPad output:

// Output:
// 0,3
// 0,45
// 13,2
// 1049
// 12492,4
// 2000

My application output:

// Output:
// 0,30
// 0,45
// 13,20
// 1049,00
// 12492,40
// 2000,00

UPDATE 1: I tried again following code in a .NET 4 console app, and a ASP.NET MVC 4 (both .NET 4 and .NET 4.5) and all worked well (no zeros). But it still did not work in my application, even when I put them in an empty action. The only different is my application (ASP.NET MVC 4) was created in VS2010 + .NET 4 and upgraded to VS2012 + .NET 4.5 later. Is it issue?

decimal d = 0.3M;
string s = string.Format(CultureInfo.CreateSpecificCulture("vi-VN"), "{0:G}", d);

Use {0:G29} instead

decimal d = 0.3M, d2 = 0.45M, d3 = 13.2M, d4 = 1049M, d5 = 12492.4M, d6 = 2000M;

var culture = CultureInfo.CreateSpecificCulture("vi-VN");

Console.WriteLine(string.Format(culture, "{0:G29}", d));
Console.WriteLine(string.Format(culture, "{0:G29}", d2));
Console.WriteLine(string.Format(culture, "{0:G29}", d3));
Console.WriteLine(string.Format(culture, "{0:G29}", d4));
Console.WriteLine(string.Format(culture, "{0:G29}", d5));
Console.WriteLine(string.Format(culture, "{0:G29}", d6));

Reference: Remove trailing zeros

It seems that this is just my application problem, not ToString("G"). Thanks for reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM