Accounting Style string format in ASP.NET - asp.net

I would like to know the easiest way to format a string as accounting style. I know how to format as currency using {0:c} but there are some differences in accounting style, for example, all the dollar signs will line up as well as all the decimal points, and negatives are expressed in parenthesis rather than with a "-" minus sign. You can find a good example of the way i would like it in excel if you format the cells as "accounting" with 2 decimal places.

Ignoring your alignment requirements, you could use
number.ToString("€#,##0.00;(€#,##0.00);Zero")
to bracket negative numbers.
To align your numbers, you'd have to format without the currency symbol, and pad the formatted numbers yourself with spaces, using a fixed width font would make this job easier for you.
EDIT:
It seems String.Format is your friend:
String.Format("{0,15:#,##0.00 ;(#,##0.00);- }", number)
where 15 is the total width of the output, and you need to append this text to your currency symbol. (Again, this aligns in fixed width only)

There's no format string shortcut (the single-character ones with default rules) for handling accounting style formats (here's a cheat sheet with the available format strings) so you'll have to write a more specific one (like Patrick's answer) or your own parsing method.
The alignment requirements would be specific to how you're displaying them. I'm assuming you are using a table, in which case you're limited by what HTML supports, and it doesn't support accounting style alignments like Excel.

In this blog there were some various formats outlined and this one seemed to be close to what you were looking for:
int neg = -10;
int pos = 10;
// C or c (Currency): It represent how many decimal place of zeros to show.
String.Format("{0:C4}", pos); //"$10.0000"
String.Format("{0:C4}", neg); //"($10.0000)"
It doesn't handle the padding (you may have to fix that yourself), but it does have the proper parenthesis.

You could do something using a variation of Patricks method. This will handle formating and alignment assuming you know the upper bound of how large a value you are dealing with:
private static string OutputAsCur(decimal val)
{
string format = " #,##0.00 ; (#,##0.00);Zero";
string frmt = val.ToString(format);
return CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + frmt.PadLeft(15, ' ');
}
Here's a simple example app to see it format:
static void Main(string[] args)
{
decimal d = 155.55m;
Console.WriteLine(OutputAsCur(d));
Console.WriteLine(OutputAsCur(d * -1));
Console.WriteLine(OutputAsCur(1002.32m));
Console.WriteLine(OutputAsCur(1002.32m * -1));
Console.ReadLine();
}

You can use a format string for String.Format to get what you're trying to accomplish. The only trick is that positive numbers, since they will not have a closing parenthesis mark, will have to incorporate a space at the end if they will be aligned with any negative numbers that will be in the column. The trick is to get that space into the string in a way that HTML will not ignore. I simply use the HTML entity which indicates a non-breaking space in HTML.
Here's sample code. First, in the aspx.
<table>
...
<tr>
<th scope="row" colspan="2">Total Revenue</th>
<td class="numeric total"><asp:Label runat="server" ID="TotalRevenueLabel" /></td>
</tr>
...
</table>
Now, the codebehind.
public const string kMoneyFormat = "#,#.00' ';(#,#.00);'-.-- '";
public void DataBind()
{
using (FinancialDataContext sql = new FinancialDataContext())
{
var periodQuery = from m in sql.Forecasts()
select m;
ForecastsResult periodData = periodQuery.Single();
decimal totalRevenue = period.Data.income_actual.Value + periodData.other_income.Value;
TotalRevenueLabel.Text = totalRevenue.ToString(kMoneyFormat);
}
}

I followed these steps for apply the "Accounting" format.
In a new Book on Excel, select a cell.
Insert data (i.e any number; for this example, add 80000).
Select (Accounting) NumberFormat as is shown in the screenshot #1:
Screenshot #1:
Select "More Number Formats".
Select "Custom".
Select any of the pre-defined formulas (see screenshot #2).
Screenshot #2:
In my case, this is the desired format for this number.
The negative side of this is that when you select the cell with the format applied on it, you wont see selected (Accounting) "in the DropDownList" Number Format.

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.

removing whitespaces from a QRegExpValidator

I have a code someone wrote and there
this->llBankCode = new widgetLineEditWithLabel(tr("Bankleitzahl"), "", Qt::AlignTop, this);
QRegExpValidator *validatorBLZ = new QRegExpValidator(this);
validatorBLZ->setRegExp(QRegExp( "[0-9]*", Qt::CaseSensitive));
this->llBankCode->lineEdit->setValidator(validatorBLZ);
as it can be seen from this code, is that validatorBLZ can accept only numbers between 0 and 9. I would like to change it, that validatorBLZ would be able to get as an input whitespace as well (but not to start with a whitespace), but it wont be shown.
Example:
if i try to copy & paste a string of the format '22 34 44', the result would be an empty field. What i would like to happen is that the string '22 34 44' will be shown in the field as '223444'.
How could i do it?
You could try using:
QString string = "22 34 44";
string.replace(QString(" "), QString(""));
That will replace any spaces with a non-space.
Write your own QValidator subclass and reimplement validate and fixup. Fixup does what you ask for: changes the input in a way that makes it intermediate/acceptable.
In your case, consider the following code-snippet for fixup:
fixup (QString &input) const
{
QString fixed;
fixed.reserve(input.size());
for (int i=0; i<input.size(); ++i)
if (input.at(i).isDigit()) fixed.append(input.at(i));
input = fixed;
}
(this is not tested)
The validate function will obviously look similar, returning QValidator::Invalid when it encounters a non-digit character and returning the according position in pos.
If your BLZ is limited to Germany, you could easily add the validation feature that it only returns QValidator::Acceptable when there are eight digits, and QValidator::Intermediate else.
Anyhow, writing an own QValidator, which often is very easy and straight forward, is the best (and most future-proof) solution most of the time. RegExes are great, but C++ clearly is the more powerful language here, which in addition results in a much more readable validator ;).

How to display an image if the value has a decimal point?

Basically in my in my aspx page I have a gridview which displays the value from my database as an image. So if a value in my database table is 5, it will be displayed as 5 images in the gridview. ie.(star.jpg star.jpg star.jpg star.jpg star.jpg)
The code:
Protected Function getrating(ByVal rate As Integer)
Dim getrating As String
getrating = ""
For i = 1 To rate
getrating = getrating + "<img src=""Images/star.jpg"" alt=""*"">"
Next
Return getrating
End Function
It's been working fine so far for whole numbers, but now I'm adding averages into my database, so any value with a decimal point(like 4.6) gives me the error
"Conversion from type 'DBNull' to type 'Integer' is not valid."
How would I go about in adding images when the value has a decimal point?
Since the field in my database has the range set to numbers 1 to 5, I like it to display another image if the value has a decimal point. ie. "3.5" would display in the gridview star.jpg, star.jpg, star.jpg, halfstar.jpg. If that made any sense lol.
Anyone have an idea on how to do doing this?
Judging by your error, it's probable that you're not even accepting decimal values and inserting the NULL value when they occur. Fix that first, make sure the result isn't DBNull, then you can make the changes to a decimal type like Double:
Protected Function GetRating(ByVal rating As Double) As String
Dim result As New System.Text.StringBuilder()
While rating >= 1.0#
result.Append("<img src=""Images/star.jpg"" alt=""*"">")
rating -= 1.0#
End While
If rating > 0.0# Then _
result.Append("<img src=""Images/halfstar.jpg"" alt=""1/2"">")
Return result.ToString()
End Function
I also took the liberty of using a StringBuilder instead of concatenating strings with +.
You need to check DBNull value (From error description).
If reader.Read() Then
IF Not reader.IsDBNull(0) Then '1st column
'If field type is decimal
Dim decimalVar=reader.GetDecimal(0)
End If
End If
If you want to do this I really recommend to use one image which contains all stars in it. So that image should have 5 Stats like:
For this demo I added a image with 120px width and 24px height. Then You need to add a like this:
Then when you want to show your stars, you need to find out the width of this with following method:
DIV width = (Rate/5) * 120
So for example 2.5 will be (2.5/5)*120 = 60! Then you need to change DIV's width to 60 and then you'll have your 2.5 rank! and will become something like:
<div style="background-image:url(http://s.codeproject.com/script/Ratings/Images/stars-fill.png);width:60px;height:24px;">
</div>
This is just a simple method which will give you an idea to expand and customize for your logic. I hope this helps :-)
Live Demo: http://jsfiddle.net/qxrub/

Replace string from character onwards

I've got a string like so
Jamie(123)
And I'm trying to just show Jamie without the brackets etc
All the names are different lengths so I was wondering if there was a simple way of replacing everything from the first bracket onwards?
Some others are displayed like this
Tom(Test(123))
Jack ((4u72))
I've got a simple replace of the bracket at the moment like this
mystring.Replace("(", "").Replace(")","")
Any help would be appreciated
Thanks
VB.NET
mystring.Substring(0, mystring.IndexOf("("C)).Trim()
C#
mystring.Substring(0, mystring.IndexOf('(')).Trim();
One logic; get the index of the ( and you can trim the later part from that position.
public static string Remove(string value)
{
int pos = value.IndexOf("(");
if (pos >= 0)
{
return value.Remove(pos, remove.Length);
}
return value;
}
aneal's will work. The alternative I generally use because it's a bit more flexible is .substring.
string newstring = oldstring.substring(0,oldstring.indexof("("));
If you aren't sure that oldstring will have a "(" you will have to do the test first just as aneal shows in their answer.
String.Remove(Int32) will do what you need:
Deletes all the characters from this string beginning at a
specified position and continuing through the last position.
You will also have to .Trim() as well given the data with padding:
mystring = mystring.Remove(mystring.IndexOf("("C))).Trim()

Formatting asp.net label when the value is sourced from a query string

Afternoon all.
A very simple one for you today from thicky Rich.
I have a label I want to display as a lovely number format i.e. {0:N0}
Now, this label text equates to a query string value.
How do I go about formatting a label's text from a query string value in one fell swoop?
I have tried this
lblTotalPurchQS.Text = String.Format("{0:N0}",Request.QueryString["totalpurchasequantity"].ToString());
but with little success.
Any ideas or pointers?
Don't use ToString on the incoming query string parameter, but convert it to an int first:
lblTotalPurchQS.Text = String.Format("{0:N0}", int.Parse(Request.QueryString["totalpurchasequantity"]));
Note:
The above is not safe code. First, the conversion may fail with a conversion exception. You should also be HTML escaping the output, in case of XSS.
This is better:
int totalPurchaseQuantity;
if(int.TryParse(Request.QueryString["totalpurchasequantity"], out totalPurchaseQuantity))
{
lblTotalPurchQS.Text = Server.HtmlEncode(String.Format("{0:N0}", totalPurchaseQuantity);
}

Resources