Change Currency Format - asp.net

I Have a field that should consist a currency, which is according to my Region is Indonesia which is IDR or Rp.
and i build it with string.format like this :
Dim price As Single = Single.Parse(Convert.ToSingle(lblAmountGV.Text))
lblAmount.Text = String.Format("{0,C}", price)
but it give me a dollar sign. and i Change the code :
lblAmount.Text = String.Format("Rp{0}", price)
but i didn't get the dot (.) and Comma(,) . so I change the code again by using FormatCurrency :
lblAmount.Text = FormatCurrency(lblAmountGV.Text, , , TriState.True, TriState.True)
but it still give me a Dollar sign, later i found how to change the CultureInfo :
by imports :
Imports System.Globalization
and on my code :
Dim culture = CultureInfo.GetCultureInfo(" id-ID")
Dim format = DirectCast(culture.NumberFormat.Clone(), NumberFormatInfo)
format.CurrencySymbol = "Rp."
var number = Decimal.Parse(lblAmountGV.Text, NumberStyles.Currency, format);
lblAmount.Text = number
but it still give me an $ sign, how to change the $ programatically?

I see a couple issues with what you posted -
this line is incorrect
String.Format("{0,C}", price)
You need to use a colon to add additional formatting arguments. If you want to format currency with decimal places than you also need to indicate the number of decimal digits. It should be something like this
String.Format("{0:C2}", price)
And this line has an extra space that causes it to fail with a CultureNotFoundException
CultureInfo.GetCultureInfo(" id-ID")
Should be
CultureInfo.GetCultureInfo("id-ID")
This code worked for me:
Dim culture As CultureInfo = CultureInfo.GetCultureInfo("id-ID")
Dim price As Double = 10.05
Dim result As String = String.Format(culture, "{0:C2}", price)
You can see it in action here
If you are familiar with LINQPad, you can paste the following into LINQPad and see the proper formatting without the dollar sign -
String.Format(CultureInfo.GetCultureInfo("id-ID"), "{0:C2}", 10.05).Dump()

Related

Format zero currency value with {0:C} in VB.Net

I am trying to format a zero currency value as an empty string, so that when the currency value is 0.00 then an empty string gets displayed rather than $0.00.
This code is part of an ASP.Net app that will display currency value to end user.
I have used following code to achieve this goal.
Question : Is it possible to achieve this by just using {0:C} format string or another version of this format string instead of using if then else coding for this? If I use ###,###,###.## as the data format string then an empty string shows for zero currency value and also I get rid of the if then else coding but for non-zero values no currency symbol shows.
If Double.Parse(Decimal.Parse(CDec(currencyValue))) = 0 Then
charValue = Nothing
Else
charValue = String.Format("{0:C}", CDec(currencyValue))
End If
UPDATE
I ended up using the following code, which is working fine. If is better than IIf because it does short-circuiting, which means that IIf will evaluate all expressions whether the condition is true or false but If will evaluate the first expression only if condition is true and evaluate the second expression only if condition is false.
Dim d As Decimal
Decimal.TryParse(currencyValue, d)
charValue = If(d = 0D, Nothing, String.Format("{0:C}", d))
I don't think there is a way using formatting to display an empty string.
But you can write it like:
charValue = If( currencyValue = 0D, "", currencyValue.ToString("C") )
using the If Operator (Visual Basic).
Also this is something I would not do:
If Double.Parse(Decimal.Parse(CDec(currencyValue))) = 0 Then
If currencyValue is Decimal:
If (currencyValue = 0D) Then
If currencyValue is Double:
If (currencyValue = 0R) Then
Also, if you are using a database and this is a Sql Server mind SQL Server Data Type Mappings
I don't think you can when using C or the other similar standard formats, since they are already defining a culture-specific format that will include a format for zero.
But if you specify your own custom format, you can specify three different formats separated by ;s, one each for positive numbers, negative numbers, and zero, respectively.
For example (giving an empty string for the zero format, resulting in blank zeroes):
charValue = String.Format("{0:#,##0.00;-#,##0.00;""""}", CDec(currencyValue))
And from what I can see, omitting the format for negative gives a default that matches the positive, whereas omitting the format for zero gives blank, which is what you're looking for, so this should be sufficient as well:
charValue = String.Format("{0:#,##0.00;;}", CDec(currencyValue))
(Using whichever custom format you wish.)
UPDATE: You can get the current currency symbol and manually put it into your custom format. IE:
Dim symbol = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol
charValue = String.Format("{0}{1:#,##0.00;;}", symbol, CDec(currencyValue))
From the sound of it, though, I think I would actually recommend doing basically what you started with, maybe with an extension method.
<Extension>
Public Function ToCurrencyString(pValue As Decimal) As String
Return IIf(pValue = 0, "", pValue.ToString("C"))
End Function
Dim someValue As Decimal = 1.23
Console.WriteLine(someValue.ToCurrencyString())
This gives you exactly what you're looking for. The exact same format as C gives, but with blank zeroes.

Input string was not in a correct format when adding session variables

I am trying to add some session values and if any of the value have a decimal value ie 12.50 I get an error that Input string was not in a correct format.?
Dim Res As Integer = Convert.ToInt32(Session("ConsultingFeeAmount")) + Convert.ToInt32(Session("FoodAndBeverageAmount"))
TotalAmount = Environment.NewLine + "Total Amount: " + Session("ConsultingFeeAmount") + Session("FoodAndBeverageAmount")
TotalAmount = "Total Amount " + Res.ToString
Use a TryParse method from the Decimal class
Dim consultAmt As Decimal
Dim foodAmt As Decimal
Decimal.TryParse(Session("ConsultingFeeAmount"), consultAmt))
Decimal.TryParse(Session("FoodAndBeverageAmount"), foodAmt))
Dim Res As Decimal = consultAmt + foodAmt
TotalAmount = Environment.NewLine & "Total Amount: " & _
consultAmt.ToString() & " " & foodAmt.ToString()
TotalAmount = "Total Amount " & Res.ToString
The Decimal.TryParse analize the input string and set the second parameter with the converted value if it is possible to convert the string to a decimal. If not the method doesn't rises any exceptions and the second parameter is let alone to its default value.
EDIT
The OP says that after the change initially suggested now it has an error message that says:
Conversion from string " Total Amount: 12.50 13.00" to type 'Double'
is not valid
The problem was the + operator used to concatenate strings when Option Strict is OFF. In that case the VB compiler confuses the meaning of the operator and tries to sum two numeric values. I really suggest to use Option Strict On and Option Explicit On because this will force your code to be more precise (no implicit conversion of types). Of course if you make this change you need an extensive retest of your application
You can read about this problem in this question/answer link
I think your problem lies in the code Convert.ToInt32. You can't pass in a decimal number there. It's expecting an integer. That occurs more than once in your code.
I am guessing the value you passed to Convert.ToInt32 are not a valid numeric ones. Make sure you check the session values are empty or not before using that.
if Session("ConsultingFeeAmount") IsNot Nothing Then
' Now use this session variable
End If
I don't know if vb.net is different than C#, but Session returns an object not a typed value. You will need to cast Session("ConsultingFeeAmount") to a decimal.
CType(Session("ConsultingFeeAmount"), Decimal)
or
CType(Session("ConsultingFeeAmount"), Integer)

How do I delete characters in a string up to a certain point in classic asp?

I have a string that at any point may or may not contain one or more / characters. I'd like to be able to create a new string based on this string. The new string would include every character after the very last / in the original string.
Sounds like you're wanting the file name from a URL. In any case, it's the same function. The key is using the InStrRev function to find the first / char, but starting from the right. Here's the function:
Function GetFilename(URL)
Dim I
I = InStrRev(URL, "/")
If I > 0 Then
GetFilename = Mid(URL, I + 1)
Else
GetFilename = URL
End If
End Function
Split it up into parts and get the last part:
a = split("my/string/thing", "/")
wscript.echo a(ubound(a))
note: Not safe when the string is empty.

how do i delete characters in a string/text of a textbox?

I have an asp.net 4 textbox control that has it's text being dynamically populated by some java script. A Google Maps call to be exact. It's giving me mileage from 1 point to another. When the text displays, it shows " 234 mi" I need to get rid of the "mi" part of this text because the text is being converted to an Int32 Updating a table in my DB.
Basically I can only have an INT. Nothing else in the text box. How do I get rid of the "mi" at the end of the text?
Thanks
C#
EB
On the postback, before you save it you could:
var saveValue = Int32.Parse(tbTarget.Text.Replace("mi", string.Empty).Trim());
If your working with a variable length of chars (say someone enters miles instead) then your must do a foreach against the string (an array of char) and check isnumeric on each char.
A simple String.Substring works also:
String leftPart = TxtMileAge.Text.Substring(0, txt.IndexOf(' '));
int mileAge = int.Parse(leftPart);
This retrieves the part of the String in the range of 0 - indexOfWhiteSpace and converts it to an int
Edit: Since the value can have decimal places (as you've commented), you need to parse it to double, round it and then cast it to int:
var txtEstDistance = new TextBox() { Text = "40.2 mi" };
String leftPart = txtEstDistance.Text.Substring(0, txtEstDistance.Text.IndexOf(' '));
double distanceMiles = double.Parse(leftPart, System.Globalization.CultureInfo.InvariantCulture);
int oDdstanceMiles = (int)Math.Round(distanceMiles, MidpointRounding.AwayFromZero);

How to declare ASP classic constants to a data type?

In asp classic and vbscript, you can declare a Const with a hexidecial value, and a date type value:
Const C_LIGHTCYAN = &hCCFFEE
Const C_STARTDATE = #1 JAN 2000#
But how can I declare currency, single or doubles data types?
Const C_LONG = 1024 '# I want this to be a LONG, not an INT!
I'm sure I've seen something like Const C_LNG = L12345 or some other prefix/suffix combination for longs or doubles but can't find the source now
You can't declare variables with data types in ASP just set the value in decleration, that should work fingers crossed.
I don't think there is currency type anyway. For double you can 1.00 etc.
Here is the CLng function for VBScript. But since you can't declare use a function for a constant declaration, and you can't re-assign to a constant, do you really have to use constants here?
While you can't declare data types in Windows Scripting (VBScript, ASP), you can assign a variable to become a type, then verify that variable's type. VBScript provides no type protections, so you're allowed to reassign a declared variable to a different type. This loose typing strategy is one root of problems.
Dim textVariable : textVariable = "Hello World!"
WScript.Echo TypeName(textVariable)
' Returns Text
Dim integerVariable : integerVariable = 6
WScript.Echo TypeName(integerVariable)
' Returns Integer
Dim objectVariable : set objectVariable = CreateObject("Scripting.Dictionary")
WScript.Echo TypeName(objectVariable)
' Returns Object
Some types require some brute force and trickery. The binary datatype is one example.
Dim generateData(1) : generateData(0) = &HFF
Dim mem : Set mem = CreateObject("System.IO.MemoryStream")
mem.SetLength(0)
mem.WriteByte (generateData(0))
Dim byteArray : byteArray = mem.ToArray()
'Returns a VB Style, "Byte()" [Byte Array]

Resources