Custom Numeric Formats for NumToString

We have a quick tip from your Uncle Pete today. Did you know you can create custom numeric formats to be used for NumToString? Why would you want to you might ask?

A client was needed to display a number with 4 decimal positions, but they wanted it to display with parentheses instead of a negative sign if it was negative. For example -21076.5900 should display as (21,076.5900).

But first a word about input / display mask. I have always struggled to get these to work properly in WEBDEV when it comes to numbers. There always seems to be some confusion between US standards of comma for thousands separator and period for decimal separator vs the French, space for separator and comma for decimal. According to this help page https://doc.windev.com/?1014015 we should be able to create a custom mask that would work, but neither I or the client could ever get it to work right.

Because of these struggles with display mask, and the fact that we use the WX FileManager for all of our projects, I find it much easier to just create a property that is used as the display value for a field and I bind the screen control to that property.

But the next challenge was, NumToString doesn’t support parentheses as a negative sign … or does it?

It turns out there is a special variable type “NumericFormat”, see the help here https://doc.windev.com/en-US/?1410089836

This allows us to define a special format to be used by NumtoString. In the code below, you can see where I created a NumericFormat to give us the desired results.

test is numeric = -21076.5900

CustomFormat is NumericFormat
CustomFormat.Notation			= nfnDecimal
CustomFormat.Sign				= nfsParenthesesIfNegative
CustomFormat.DigitsAfterPoint	= 4
CustomFormat.MinimumLength		= 8
CustomFormat.ThousandSeparator	= ","
CustomFormat.FillCharacter		= ""
Info(NumToString(test, CustomFormat))

All that would be left to do in one of our applications is to turn this into a property on the record class.

Note: If someone has figured out the magic of custom numeric mask in WEBDEV please let me know!


Leave a comment