Nov 21, 2012

Headaches with trailing zeros in double value

I have a textbox on ASP.NET webforms page.
It should allow for double values fixed to 5 decimal places.
Initially I've used Infragistics Web numeric edit control.
You set it's minDecimalPlaces and DataType to "double" and everything is fine.
There is a catch.
If you enter :
1,2 it becomes  1,20000
; which is quite ugly.

So client came along and said fix it. I hate those trailing zeros, loose them.
Unfortunately after hours I could'nt find way to apply formatting without trailing zeroes so it all defaulted to use of regular textbox with server side formatting.

No, it does not filter chars and you can enter any chars.

The tricky part was this part executed in Autopostback:

If Double.TryParse(rowValue, controlValue) Then control.Text = String.Format("{0:G}", Math.Round(controlValue, NUMDECIMALPLACES))

After rounding to desired number of decimals "G" formatting must be used to suppress scientific notation 1E-5 etc.
Any other like F5 etc. generate again trailing zeros.

Here are some links on subject:


http://msdn.microsoft.com/en-us/library/26etazsy.aspx
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
http://blogs.msdn.com/b/kathykam/archive/2006/03/29/net-format-string-101-c_2300_-strings.aspx
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

No comments:

Post a Comment