Last post Feb 06, 2018 10:36 PM by PaulTheSmith
Feb 05, 2018 10:09 AM|EssCee|LINK
I have the below code which was picked up from a VB .Net project many years ago and converted to C#.
Strings.FormatNumber(Convert.ToSingle(ProductPrice), 2, TriState.True, TriState.False, TriState.False);
The code had to have VB .Net as a reference in order for it to work. I would like to remove all references to VB .Net and "upgrade" it where/if possible.
Strings.FormatNumber - Seems to be a string and formatting the number to your own requirement. So for now i would have it as
however the remainder is throwing me off target. So looking at MSDN https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.formatnumber(v=vs.110).aspx
Convert.ToSingle(ProductPrice) - is the value i want formatted.
2 - number of digits after the decimal.
TriState - although this can be converted to the relevant integer i.e. if its true then 1 else 0 i have a feeling this would add additional numbers to the value once its formatted.
So not sure if i should import the VB .Net dll or if there is a better way of converting the code?
Feb 06, 2018 02:37 AM|Cathy Zou|LINK
Strings.FormatNumber Returns an expression formatted as a number.
You could use String.Format method in C# to format number.
For more details, please refer to the similar thread below:
Feb 06, 2018 10:36 PM|PaulTheSmith|LINK
When converting from one language to another you should try very hard not to do a literal, expression for expression conversion. It is much better to use the original code as a specification and write new code to that specification.
The code snippet you have shown converts a ProductPrice (big hint - sounds like something to do with money!) to a string. The code does not add a currency symbol to the string but it does ask that there be at least one digit before the decimal point and
exactly two after the decimal point. So, the code should produce results like
0.00 123.45 1.98 4267859.00 and -1234567.89
Notice that the code specifically says not to group digits and not to put negative numbers in parenthesis That is
(34.56) for a negative number is wrong
123,456.78 for a big number is wrong.
Before creating a C# program to implement this specification I would want to know what the type of ProductPrice is. If it is a string then I would be asking why? It obviously refers to a numeric quantity. Then I would fix it so that it is a numeric quantity.
Once you have ProductPrice as a numeric (int, single, decimal, double, etc) value then the expression becomes
If ProductPrice absolutely, positively for some bizarre reason has a 100% requirement that it not be numeric then the code would be
Convert.ToSingle(ProductPrice).ToString("0.00"); // Big Boss "Insert name here" demands that ProductPrice is not a number
(Don't forget the comment so that the next person working on the code understands the very strange requirement)