Convert string to currency format without casting to numerical value first - vb.net

This code -
Convert.ToDecimal("28.9100000000000000").ToString("c")
will convert a string containing a decimal value to a nicely formatted currency value. Is there anyway to do this without first converting the string value to a decimal?

In order to preserve culture specific currency attributes (currency symbol, separators and precision), your current approach looks like the best one.
If you know the precision and don't care about cultures, you can do some simple string manipulation:
"$" & myString.Substring(0, myString.IndexOf(".") + 3)

A simple method that I use:
MoneyString = string.format("{0:C}",DecimalValue)

How about this?
decimalString = "28.910000000000000000"
currencyString = "$" + decimalString.SubString(0, decimalString.IndexOf('.') + 3)
Of course, if you're going to do this you also need to worry about locale settings. Probably just as easy to do the numeric conversion, and let the framework do the formatting for you.

Related

How can I omit the first character for value in vb.net?

I have this var:
Dim number as decimal = -61.52
and I want to delete the first character to be like this:
61.52
I tried to do this. but doesn´t work:
number = Trim(Left(number , Len(number ) - 1))
How can I do this?
You're looking for Math.Abs(), which forces a number to not be negative.
If you really want to treat a number as a string and then do string manipulations on it, you want to use the ToString method on your number. This will let you specify how you want the number formatted.
Dim NumberAsString As String
NumberAsString = number.ToString()
NumberAsString = NumberAsString.SubString(1, NumberAsString.Length - 1)
Note: you shouldn't rely on the default implementation as it will use the current UI culture and not guaranteed to give consistent results if executed under different cultures than when you developed it.

Formatting Short Text as Numbers

I've got a column called Amount, with a lot of numbers looking like this:
67000.00000000000000000000
Some of the columns have 2 numbers after the decimal that need to be retained.
Which should amount to $67,000.00
But my problem is, when I format it into currency or numbers, I get MUCH larger numbers than i would like, looking like this:
6.700.000.000.000.000.000.000.000,00
How can I get it into the right format?
Edit: For this scenario, the user was using ACC2013 and the Field Type was Short Text. The method of conversion that succeeded was : CCur(Val(FieldNameHere))
CCur(YourFieldName)
This will convert it to a currency format.
CLng(YourFieldName)
This will convert it to a long integer format. (It will cut off the decimals)
If you're looking for a reference, Microsoft has a few examples and goes into brief detail about some of these conversion functions.
CCur(Replace("67000.00000000000000000000", ".", Format(0, ".")))
You have to replace point symbol to actual decimal separator before conversion. Because you can't know actual seprator, choosen in regional settings, you have to find it out - and such Format() operation does dirty work.

Format fractional separator of C# decimal

I'm interacting with a 3rd party system that requires me to send it decimal numbers where s decimal comma must precede the fractional part. If the value has no fractional part the decimal comma must still be present.
So for example
decimal d = 123.45M; //needs to become 123,45
decimal d2 = 345M; //needs to become 345,
Is there an elegant way of formatting .net decimals for this purpose?
It seems like your 3rd party system might simply be using a different Culture. You can set the CultureInfo that you want to use and formatting will do what it needs to for that culture including dates, numbers, and currency.
Example:
CultureInfo culture = new CultureInfo("fr-FR");
Console.WriteLine(string.Format(culture, "{0}", 123.45M));
Output:
123,45
Even if you want to keep the current culture but for a given purpose override just one thing you can override them by:
culture.NumberFormat.NumberDecimalSeparator = ",";
Edit: I've found no way of doing the trailing decimal separator using only the built-in numeric formatting but you might be able to find something looking through the custom numeric format strings. Otherwise you may have to resort to simply testing for d2 % 1 == 0 and manually adding the decimal separator.
Example:
public static string FormatWithTrailing(decimal number)
{
// Change the following culture to the actual desired culture
CultureInfo culture = new CultureInfo("fr-FR");
return number % 1 == 0
? number.ToString(culture) + culture.NumberFormat.NumberDecimalSeparator
: number.ToString(culture);
}
Outputs:
123,45
345,

CStr() vs. Str() vs. .ToString()

I want to know what exactly are the differences between CStr(), Str() and .ToString()?
Label1.Text = CStr(Int(Rnd() * 10))
and
Label1.Text = Str(Int(Rnd() * 10))
and
Label1.Text = Int(Rnd() * 10).ToString
If I use this condition:
If Label1.Text = "7" Then
'Some code here
End If
Str() doesn't work here. What's the difference?
ToString will call the .ToString() function on a particular instance.
In practice, this means that it will throw an exception if the object in
question is Nothing. However, you can implement .ToString() in your own
classes to get a useful string representation of your object, whereas
CType/CStr only work with built-in classes and interfaces.
CStr and CType(expression, String) are exactly equivalent (I'm not
sure where the other poster got the idea that CStr is faster). But they
aren't really functions, they're compiler directives that will emit very
different code depending on the declaration of expression. In most
cases, these directives call a bunch of internal VB code that tries to
get a reasonable string out of expression.
DirectCast(expression, String) assumes that the expression in
question really is a String and just casts it. It's the fastest of all
these options, but will throw an exception if expression is anything
other than a String.
As an Addition to the VBA/VB6 Environment where we have no ToString():
Str() is not aware of international representation. The decimal separator always is a dot (.).
As already mentioned above it prefixes the resulting string with a blank in case of positive values.
There also exists Str$(). The difference to Str() is the return type:
Str() returns a variant of type string, Str$() returns a string.
And Str$() is slightly faster then Str().
CStr() in contrast is aware of international representation. The decimal separator depends on the Windows international settings.
No additional prefixing for positive values will be done.
So if you need to convert a value type to a string and have to ensure a dot as a decimal separator and no prefixing blank, then use this syntax:
Dim d As Double
d = 123.456
Dim s As String
s = Trim(Str$(d))
I don't know about ToString() and i don't know about VB.NET
But in VB6 (Visual Basic 6):
Both of Cstr() and Str() converts values to string. but Cstr() is better because:
Str(): After converting to string it adds 1 space before positive numbers. for example: Str(22) > " 22"
Cstr(): After converting to string it never adds the above extra space - For best result use it with Trim() - Trim(Cstr(Variable))
Although not a problem in the code in the question, it is important to mention that Str() only converts numerical expressions to string, gives an error in other cases, so don't use it for converting values of a cell.
My answer is str() is evil as it always prepends a space for the sign character so if you are comparing values it fails. Instead use CStr() instead which does not do this.
You may comes across business logic that tries to do this:
Eg:
Dim sVar as String = "1"
Dim i as Integer = 1
console.write( cstr(i) = sVar )
Which outputs:
False
I lost a couple hours on this one as the code was quite deep in old code and was very difficult to grok in production environment where logging based debugging was all that was available.

Decimal.toString() for any region using VB.NET

I have an application that deals with currency. For display purposes I use the nifty VB FormatCurrency function which will format based on the OS's region setting. So, if in France you might get 123,45 whereas in the US you would get 123.45.
To perform the calculation on these amounts I use CDec() to convert to decimal.
My problem is that when I convert the Decimal to a String using toString() it formats according to the currently set region. I need to be able to always convert the decimal into a String representation for the US, i.e. with decimal points.
I thought I would be able to do something similar to this:
.toString("#0.00")
Try:
value.ToString("C", CultureInfo.InvariantCulture)
More info here:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
The "C" is to format for currency, but you can use lots of different format strings. If you really want it formatted for "US" rather than the invariant culture you can do this:
value.ToString("C", CultureInfo.CreateSpecificCulture("en-US"))
This
Dim dec As Decimal = 1.25D
Dim s As String
s = dec.ToString("C2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
produces $1.25
This
s = dec.ToString("N2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
produces 1.25
Try passing InvariantCulture into your ToString() method:
Dim dec As Decimal = 1.25D
dec.ToString(System.Globalization.CultureInfo.InvariantCulture);
//writes 1.25