Thursday 13 March 2008

ASP.NET Ajax - Number.format doesn't round

I recently came across an annoying inconsistency between Decimal.ToString()/String.Format() on the server, and Number.format()/Number.localeFormat() on the client javascript. The client code doesn't round!

Try it yourself. Open firebug on an ASP.NET Ajax website (this one will do), open the Console, and type

123.456.format("N2")

This simple line of code tells it to format the string as a decimal to 2 decimal places. The resulting output, 123.45, is WRONG!

Try this using .NET on the server 123.456.ToString("N2") and you will get the correctly rounded value - 123.46.

How to fix this? As I have pointed out before, with JavaScript, you can override any function by just defining it later on in the HTML. So I created a new script file with a new definition of the Number._toFormattedString() method, which is the private method used to do the formatting. I then include this file in the <scripts> of my ScriptManager on the master page. Script references are always loaded after ASP.NET Ajax internal scripts itself.

It's not that hard to fix - you just have to apply some rounding logic to the existing code, which features the following line:

if (rightDifference > 0) {

  right = right.slice(0, precision);

}

This just slices the end of the string off and doesn't even consider doing any rounding!

Now there are many ways to perform rounding which I won't go into here, but if you want to check it you can download the replacement script here. Simply include this in an <asp:scriptreference> in the scripts section of your script manager and rounding should work fine.

Hope this helps.

No comments: