Razor Format Decimal? value in view - c#

I'm currently working on an ASP.NET MVC 4.6 application. I try to format a Decimal? property to a correct string format.
My property looks like this:
public decimal? Amount{ get; set; }
The data from the database looks like this: 10000,99
My desired outpout should actually be: € 10.001
no decimal values and no , (comma) is allowed.
In my Razor view I currently use:
#String.Format("{0:N0}", Model.Amount)
This works almost fine, though I get this result: € 10 000 which is wrong unfortunately.
Do you know hot to solve this in ASP.NET MVC Razor? Desired output € 10.001
Thank you!!!!

String.Format() has an overload which accepts IFormatProvider. Simply pass the desired number format there:
var c = new System.Globalization.CultureInfo(""); // create InvariantCulture
c.NumberFormat.NumberGroupSeparator = ".";
var s = String.Format(c, "{0:N0}", 10000.99);

Related

Remove Decimal form String if equals to ".00"

Im having alot of problems trying to take out the decimal part of my string,
the string comes from a var type in my view like this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro))**
temp.Rubro is my String part that can be ".00" or ".XX"
however i need to take the decimal part of the string only when its value is ".00"
since i have some values of the dashlist have important decimal parts.
Is there a way to take the decimal part of a string only if it equals to ".00"???
The output im trying to get is:
From XX.00 -> XX
From XX.12 -> XX.12
both kinds are on my list
Try this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro).Replace(".00", ""))
You can try using
String.Format("{0:G29}", decimal.Parse(temp.Rubro)))
Whereas all the below formats achieve the same results.
string.Format("{0:G29}", decimal.Parse("2.00"))
decimal.Parse("2.00").ToString("G29")
2.0m.ToString("G29")
You can use ToString() with the General ("G") Format Specifier to achieve the desired result. Trailing zeros are truncated when using this format string with a precision specified. In order to prevent rounding in any situations, you will need to set the precision to the maximum allowed for decimals (29).
Simple trick...
You can parse the string and it will automatically remove the decimal places
try following
private static void ParseDouble()
{
string sDouble = "12.00";
double dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
sDouble = "12.14";
dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
}
Your output will be
12
12.14
Hope this helps.
I will suggest you to use accounting.js plugging which is pretty straightforward. I have used it in some projects and as of today I cannot complain. Otherwise, you could do something like this,
var x = temp.Replace(".00","").Trim();

What does the 0 in "{0:MM dd yyyy}" do?

I'm new to the C#/MVC world. I spend a lot of time today figuring out how to display a DateTimeOffset object in the format i want. Finally got it working this way.
Html.TextBoxFor(model => model.DeliveryDate,"{0:MM/dd/yyyy}",
new { htmlAttributes = new { #class = "datepicker" } })
But I still don't understand the importance of '0' in the format string. the page breaks if i replace the 0 with any other number or totally remove it. Can someone help me understand this?
From String.Format Method
The {0} in the format string is a format item. 0 is the index of the object whose string value will be inserted at that position. (Indexes start at 0.) If the object to be inserted is not a string, its ToString method is called to convert it to one before inserting it in the result string.
That's a format string with parameters (like used in e.g. Console.WriteLine, or string.Format). The {0} would be the placeholder for the first argument, and {0:mm/dd/yyyy} is simply a format string to convert the first argument to a string.
When you use the string.Format you can pass the space for arguments like {0}, {1}, etc which is the indexes you pass as arguments for the method. It is the same for asp.net razor helpers.
You also can provide the format after the index separating by :, for sample: {0:0.00} as format for a number with 2 decimals places or {1:dd/MM/yyyy} for dates etc.
String Interpolation
There is a new way to implement it using the String Interpolation. Basically, you can concat the values on your string without generating new strings. For sample:
var i = 18;
var s = $"You are {age} years old.";
Since you start the string with $, you can pass arguments between { and }. You also can use the same formats to format your data as you use on string.Format. For sample:
var today = $"Today is {DateTime.Now:D}";
var date = DateTime.Now.Add(1);
var tommorrow = $"Tommorrow is {date:dd/MM/yyyy}";
See the documentation for String.Format():
https://msdn.microsoft.com/en-us/library/system.string.format.aspx
In a nutshell, when the model is rendered to HTML text, the DeliveryDate object value will be passed to String.Format(), where {0} indicates the index of the first value in an array of values being passed to Format(). So {0:MM/dd/yyyy} just means to format the first value in the array using date components. Basically, it will do something like this internally:
String s = SomeValueArray[0].ToString("MM/dd/yyyy");
0 is a placeholder for your argument / property (in this case) DeliveryDate.. Similar to String.Format examples... so when your View is rendered.. the 0 will be replaced with whatever value that DeliveryDate is holding in the format MM/dd/yyyy

formatting ajax.actionlink text to display

I have a decimal data type in my model and an annotation to format it so it adds commas after 3 digits:
[DisplayFormat(DataFormatString = "{0:#,###0.00}" + " (USD)")]
public decimal PaidAmount { get; set; }
when I have any DisplayFor(m => m.PaidAmount) the formatting displays correctly (1,200.00 USD). However, in Ajax.ActionLink the first argument takes a string for the text to display so I can't use a lambda expression (m => m.PaidAmount). When I do:
Ajax.ActionLink(Model.PaidAmount.ToString(), //rest of link params)
the formatting doesn't apply to the link text, it shows just a bunch of numbers without commas (1200.00 USD, note there is no comma after the 1)
my guess is that using the capital 'M'odel version of model loses its annotation properties, is there a way to go around this and apply the formatting to the ajax.actionlink?
You can use
#Ajax.ActionLink(string.Format("{0:#,##0.00 USD}", Model.PaidAmount), ...)
Note I think you mean 0:#,##0.00 not 0:#,###0.00 (i.e. 10,200.00 USD, not 1,0200.00 USD)
Data annotations will not work in this case as they are checked in HtmlHelpers and won't affect regular ToString.
You can create an extension method to format your number an call it in your view:
public static class Extensions
{
public static string ToCurrency(this decimal number)
{
return number.ToString("{0:#,###0.00}") + " (USD)";
}
}
In you view: (don't forget to reference the Extensions class either directly in the view or in web.config under views folder)
Ajax.ActionLink(Model.PaidAmount.ToCurrency(), //rest of link params)

How can I format string values using a mask in a generic way?

Background: We have a system that receives data from another backend system. We handle the displaying of that data, and we have our own XML templates to control how certain things are displayed (i.e. we have our own column templates to dictate what the column headers are, etc.) One thing we would like to support is the ability to provide a mask for these column templates that would apply to the values coming from the backend. Below is a scenario that I'm having trouble with.
Problem: I can't seem to get a simple string format working. I'd like to format a STRING value of four digits (i.e. "1444") in a time format (i.e. "14:44"). I've tried:
String.Format("{0:00:00}", "1444")
Note the importance of the input being a STRING. If I supply an int value, the format will work. The reason I cannot use this is because all the data we receive from the backend is in string format, and we'd like for this to be generic (so casting isn't really an option).
By generic, I mean I'd like to specify a mask in our own XML templates, something like:
<MyColumnTemplate Id="MyColumn" Mask="00:00" />
and to use that mask in a string format call for string values? If the mask fails, we could just simply return the original value (as the String.Format() method already does by default).
Edit: To help clarify, here is a simplified version of what I'd like to be able to do in code:
string inputValue = "1444";
string maskValueFromXml = "00:00";
string mask = "{0:" + maskValueFromXml + "}";
string myDesiredEndResult = String.Format(mask, inputValue);
The thing is you are working string to string,since you ask for time and phone number they are all numbers then try this trick(if we can call it that :)):
string result = string.Format("{0:00:00}", int.Parse("1444"));
For phone number:
string result = string.Format("{0:000-000-0000}", int.Parse("1234560789"));
You can even place your desired masks in a dictionary for example and do this:
Dictionary<string, string> masks = new Dictionary<string, string>();
masks.Add("Phone", "{0:000-000-0000}");
masks.Add("Time", "{0:00:00}");
string test = "1234560789";
string result = string.Format(masks["Phone"], int.Parse(test));
Try with DateTime.TryParseExact, e.g:
DateTime dateEntered;
string input = "1444";
if (DateTime.TryParseExact(input, "HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateEntered))
{
MessageBox.Show(dateEntered.ToString());
}
else
{
MessageBox.Show("You need to enter valid 24hr time");
}
After that, you can use string.Format, predefined formats on MSDN.

Deserializing Client-Side AJAX JSON Dates

Given the following JSON Date representation:
"\/Date(1221644506800-0700)\/"
How do you deserialize this into it's JavaScript Date-type form?
I've tried using MS AJAX JavaScrioptSerializer as shown below:
Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/")
However, all I get back is the literal string date.
Provided you know the string is definitely a date I prefer to do this :
new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10))
Bertrand LeRoy, who worked on ASP.NET Atlas/AJAX, described the design of the JavaScriptSerializer DateTime output and revealed the origin of the mysterious leading and trailing forward slashes. He made this recommendation:
run a simple search for "\/Date((\d+))\/" and replace with "new Date($1)" before the eval
(but after validation)
I implemented that as:
var serializedDateTime = "\/Date(1271389496563)\/";
document.writeln("Serialized: " + serializedDateTime + "<br />");
var toDateRe = new RegExp("^/Date\\((\\d+)\\)/$");
function toDate(s) {
if (!s) {
return null;
}
var constructor = s.replace(toDateRe, "new Date($1)");
if (constructor == s) {
throw 'Invalid serialized DateTime value: "' + s + '"';
}
return eval(constructor);
}
document.writeln("Deserialized: " + toDate(serializedDateTime) + "<br />");
This is very close to the many of the other answers:
Use an anchored RegEx as Sjoerd Visscher did -- don't forget the ^ and $.
Avoid string.replace, and the 'g' or 'i' options on your RegEx. "/Date(1271389496563)//Date(1271389496563)/" shouldn't work at all.
A JSON value is a string, number, object, array, true, false or null. So this is just a string. There is no official way to represent dates in JSON. This syntax is from the asp.net ajax implementation. Others use the ISO 8601 format.
You can parse it like this:
var s = "\/Date(1221644506800-0700)\/";
var m = s.match(/^\/Date\((\d+)([-+]\d\d)(\d\d)\)\/$/);
var date = null;
if (m)
date = new Date(1*m[1] + 3600000*m[2] + 60000*m[3]);
The regular expression used in the ASP.net AJAX deserialize method looks for a string that looks like "/Date(1234)/" (The string itself actually needs to contain the quotes and slashes). To get such a string, you will need to escape the quote and back slash characters, so the javascript code to create the string looks like "\"\/Date(1234)\/\"".
This will work.
Sys.Serialization.JavaScriptSerializer.deserialize("\"\\/Date(1221644506800)\\/\"")
It's kind of weird, but I found I had to serialize a date, then serialize the string returned from that, then deserialize on the client side once.
Something like this.
Script.Serialization.JavaScriptSerializer jss = new Script.Serialization.JavaScriptSerializer();
string script = string.Format("alert(Sys.Serialization.JavaScriptSerializer.deserialize({0}));", jss.Serialize(jss.Serialize(DateTime.Now)));
Page.ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", script, true);
For those who don't want to use Microsoft Ajax, simply add a prototype function to the string class.
E.g.
String.prototype.dateFromJSON = function () {
return eval(this.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
};
Don't want to use eval? Try something simple like
var date = new Date(parseInt(jsonDate.substr(6)));
As a side note, I used to think Microsoft was misleading by using this format. However, the JSON specification is not very clear when it comes to defining a way to describe dates in JSON.
Actually, momentjs supports this kind of format, you might do something like:
var momentValue = moment(value);
momentValue.toDate();
This returns the value in a javascript date format
The big number is the standard JS time
new Date(1221644506800)
Wed Sep 17 2008 19:41:46 GMT+1000 (EST)

Categories