C# Custom display formatting for String fields - c#

I would like to be able to apply the following display masks in c# to doubles to produce formatted strings.
For example I want the following display masks:
0;(0) to produce a format like 126524
0,.00;(0,.00) gives 183.94
Total Spend: €0,.00;(0,.00) -> "Total Spend €12.34"
0 Days -> "0 Days"
The display masks are input by a user so can be wide in nature. They can also contain text. I have been able to do similar using a DevExpress AspxGridView, a column has a DisplayFormatString that I can use.
e.g. I have a variable named FormatString (e.g. "Total Spend: €0,.00;(0,.00)") which a user enters, I can assign to a grid column like:
columnDisplayFormatString = FormatString
I need to do something similar in a Web Service so can't use any third party UI components.
I know I can always parse the format string and derive the parameters needed for String.Format but this could get quite messy.

There's alot of information available here about string formats:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Related

How do I add decimals in Xamarin Forms Entries using C#

For starters I'm very very new to writing code! :)
What I have so far...
So far I've used Xamarin.Forms to create a user interface for a sort of specialized calculator. I'm using a Grid Layout containing: a first column of Labels, a second column of Entries (that I have named in Xaml), and a third column of Steppers (so I can change the entries by typing or using the stepper). These 3 views on each row repeat for several rows with different label text on each row and at the bottom of the Grid Layout I have an Entry for the output.
The problem...
Basically, I want to buy a certain product at different weights and prices...among other criteria....and I want to quickly figure out how much money I'll make at a future possible sale price. Simply put... I'm trying to add/subtract/multiply/divide using Xamarin.Forms Entries. I've looked everywhere and can't seem find anyone giving an example of how to do this. I've tried different methods and usually end with an error of not being able to convert the Xamarin.Forms entry to a string...So I'm back to zero. Can I get an example of a Method where I would be able to add/subtract/multiply/divide 2 Xamarin.Forms Entry views together in the C# code behind? This seems very simple to me...what am I missing??? Is there a thread/article/video somewhere that I haven't found that covers this?? And like I said, I'm very new so the answer is probably very simple.
Thanks in advance!
Steven
Entries deal with strings, not numeric values, so you need to convert them before doing calculations.
var amount = Decimal.Parse(EntryA.Text);
var price = Decimal.Parse(EntryB.Text);
var total = amount * price;
// you can use a format string as an argument to ToString()
// to control the output - ie, how many decimals, commas, etc
LabelTotal.Text = total.ToString();
In a real app you will want to validate the input in case the user enters text instead of a value number (the Parse method will throw an exception if the input is bad);

RDLC text overflow behavior

I'm working on converting an older reporting format into RDLC and am running into a problem. In a few edge cases a numeric value overruns its allotted display space -- it's, let's say, '10000%', and I can't just set "CanGrow" to false and let the field truncate since the percent sign must be visible.
In the original reporting format a field too big for its allotted display space just displayed as a bunch of asterisks, so I've got a question in two parts:
1) Is there a way to format the data in RDLC so it displays an alternate string if it runs over a certain value?
2) Is there a way to apply that format for printing only, so that on exporting the data to, say, Excel (with Report.Render) the field will still say '10000%'?
For posterity, what worked here was combining the Globals!RenderFormat field with filtering based on the value. For example
IIF(Globals!RenderFormat.Name Like "excel*" Or
(Fields!Percent1.Value > -10 And Fields!Percent1.Value < 100),
Fields!Percent1.Value, "******")

Validate parameters and string format

I need to verify if a string format has correct number and position of parameters.
In my system advanced users (administrators) can configure a option with string format and select the params in combobox, one specific combobox to position in format.
To save I need verify if this configuration is correct.
This is to generate a unique code to a record, this code is specific for each client.
In my screen I have a text box to the format, that can contain up to 6 items (or less), for each item i have one combobox.
The comboboxes contains a type of the value (ex. sequence, year, number, nothing (in case it's not required, etc).
I need verify if the format is correctly (ex. {0}-{1} is correct and {0}-{1}.{3} is wrong) and respective comboboxes are selected (ex. {0}-{1} require select a type in combobox 0 and 1)
--update--
I have resolved this question verifing the number of parameters in the string format is match with the number of values selecteds and the order of the values selecteds (ex. if the user keep any value empty and selected the next I have assumed this is incorrect) and I try generate a string with the format and values informed
To match a string to a particular pattern you should look into Regular Expressions.
It looks however, like there is more to it than simply pattern messaging - like maybe the user should be able to specify the desired pattern at run time? The question is a little unclear to be honest so I don't understand your full requirement.

Formatting a string to display custom decimal values

I'm trying to format some doubles properly so that they will display properly for my uses (I'm building a statement in Devexpress, so I'm working with a lot of numbers).
Here are the basic formatting rules I'd like to have happen:
1000.2 -> 1,000.20
1000 -> 1,000
1000.22 -> 1,000.22
Is this possible using string formatting in C#? I've tried the following, but not been able to achieve my goal:
#,#.## - gives me 1,000.2 for the first value
#,#.#0 - gives me 1,000.00 for the second value
#,#.00 - gives me 1,000.00 for the second value
EDIT: Some more information. DevExpress gives me the ability to use string formatting to set up the values after they've been bound to the report. We're doing it at report time (and not at calculation time in the behind the scenes code) because we use the Sum function within the tables that DevExpress offers us. The reason we do THAT is so that we can minimize calls to our database by doing one large pull of data, then using that table over and over again in the statement and filtering based on the restrictions within.
EDIT EDIT:
Based on the feedback I've receieved here in the comments, it's not possible to perform the formatting I'd like to do with only providing a string format; I would need to insert some code either when I provide the data to the report (and then remove any and all formatting from the report) and perform all summing functions at the code level (to ensure that the sum values have the expected decimal places), or I would need to accept .00 at the end of, for example, some amount of yen (100 JPY would never be represented as 100.00 JPY, as an example).
This is a bit of an esoteric case, but it's good to know!
You can use string formatting coupled to a simple if condition. To shorten it's use, you can also make it an Extension method. It can look like this :
public static string FormatConditionnaly(this double input)
{
return input % 1 == 0 ? input.ToString("#,0") : input.ToString("#,0.00");
}
Basically, if you number does not contain any decimals (the % 1 == 0 check), you format it without decimals. If it fails the check, you add the two zeroes.
It is used like that :
const double flatNumber = 1000;
string result1 = flatNumber.FormatConditionnaly(); //1,000
const double numberWithDecimals = 1000.5;
string result2 = numberWithDecimals.FormatConditionnaly(); //1,000,50
Bit of a hack but you can give this a try:
s = String.Format("{0:N2}", 1000).Replace(".00", "");
Use the "N" format specifier as the format string when you call ToString(); See here
For example:
int intValue = 123456789;
Console.WriteLine(intValue.ToString("N2",
CultureInfo.InvariantCulture).Replace(".00", "");
You can customize group sizes etc. as needed.
Why don't you format the values before binding to DevExpress control using plain old C# (Assuming you are doing a bind, as you have not given sufficient details.)
In c# the Math.Round() should do the trick.
Example Math.Round(doubleValue,2) where the second parameter is the number of decimal places.
EDIT:
#,##0.00
I Do not have DevExpress controls to test my solution but I did find http://documentation.devexpress.com/#windowsforms/CustomDocument1498 online (not sure if you see it already).
It seems you can use the Number or Currency masks.
Also take a look at the Zero Placeholder under the custom section. based on the description, '0' is filled where the user has not supplied a value.
example: 123.4 --> 123.40
If the string that you're trying to format is in an XRTableCell of an XtraReport instance, you can handle the BeforePrint event on that cell to format its text. This event is triggered anytime that the report is rendered. Call GetCurrentColumnValue to retrieve the value that you want to format, use any of the code methods from the previous answers that will work for you, and then set that cell's text with your formatted string. Using #dweeberly's answer:
private void OnBeforePrint(object sender, PrintEventArgs e)
{
object value = this.GetCurrentColumnValue("YourField");
if (value != null)
{
yourCell.Text = String.Format("{0:N2}", value.ToString()).Replace(".00", "");
}
}
Based on the feedback I've receieved here in the comments, it's not possible to perform the formatting I'd like to do with only providing a string format; I would need to insert some code either when I provide the data to the report (and then remove any and all formatting from the report) and perform all summing functions at the code level (to ensure that the sum values have the expected decimal places), or I would need to accept .00 at the end of, for example, some amount of yen (100 JPY would never be represented as 100.00 JPY, as an example).
This is a bit of an esoteric case, but it's good to know!

Data Annotation Phone Number Conversion

I want to gracefully convert phone number input from my users into a specific phone number format.
I would like convert this with a dataAnnotation, Just as
[dataType(dataType.Date)] displays a dateTime as a string
Ie:
0205938472 into +61205938472
02 0593 8472 into +61205938472
0593 8472 into +61205938472 (I will assume the area code from where
they live or if its a mobile)
02-0593-8472 into +61205938472
Etc, I also want to convert the other direction:
+61205938472 into 02 0593 8472 (Or whatever format i choose)
I want to do this to promote readability for the user but retain a strict data type in the database.
Questions
Is using a dataAnnotation in this manner considered bad practice?
How would I actually write the dataAnnotation( /However you would do it)?
(please include some code)
Edit: to clarify, i do not want someone to write the extension for me, I would just like an example of key pieces of code and implementation.
Please Note
These are Australia, New Zealand and internationally formatted
numbers being stored as internationally formatted numbers.
And International Formatted numbers being converted to Australia, New Zealand or internationally formatted depending on the user's location (which i can determine)
Depending on the UI you're using, you might be able to do this using a:
ASP.NET: Custom binding code (see example)
ASP.NET MVC: ModelBinder
WPF: CustomBinder
Windows Forms: Custom Converters/Editors
As parsing and formatting usually happens in the UI layer, I doubt you will find a solution that works at the data/model layer and which will work universally or which can do more than just validation.
In the data annotations namespace, there is a DataType.PhoneNumber which you can attach to your properties. Though you, yourself, remain responsible to do the parsing and the formatting using the appropriate display technology.
Data annotations and datatype are used for validation, not for converting values. The datatype is mostly used so that the validation knows where to start guessing.
2. That is asking too much for someone to code an extension like that, especially without showing any effort.
You can use DataTypeAttribute like so:
[DataType(DataType.PhoneNumber)]
public string PhoneNumber{get; set;}

Categories

Resources