strange string format percent c# output - c#

does anybody have an idea why following code outputs 1000% for RebatePercent=10 :
return RebatePercent > 0 ? $"{RebatePercent.ToString("0%")}" : "-";
I didn't find anything to output 10%
thx

you can use as:
RebatePercent > 0 ? String.Format("{0}%", RebatePercent) : "-";
and in C#6:
RebatePercent > 0 ? $"{RebatePercent}%" : "-";

If you want to keep the use of string interpolation then you can just:
return RebatePercent > 0 ? $"{RebatePercent.ToString()}%" : "-";

Related

Convert String to Currency

Im trying to detect if my string has a lenght > 4 convert it to my local currency otherwise make it display no decimal's something like this:
This is my code:
var listDay = data.Where(c => c.Fecha >= actualDate && c.Fecha <= actualDateMax).ToList();
var haveDataDay = listDay.Count() > 0;
<h4 class="semi-bold">
#if (haveDataDay)
{ #valueDateDay.ToString("F2") }
else
{ #this.FP("lbl.loader.nodata") }
</h4>
But i dont know how to check this
Someone has any idea?
There's probably a more elegant way to do this but this works just fine:
var valueDateDay = 1000;
Console.WriteLine(valueDateDay.ToString(valueDateDay.ToString().Length > 4 ? "N0" : "C2"));
valueDateDay = 100000;
Console.WriteLine(valueDateDay.ToString(valueDateDay.ToString().Length > 4 ? "N0" : "C2"));
See it in action
Not sure if I understand what your variables mean but try:
string currency;
currency = valueDateDay.ToString().Lenght > 4 ? "NO" : "C2";

Input string was not in a correct format. C# SQL

I am putting SQL values inside <td> and this line below it's causing a format error, i don't know if the parsing is incorrect or missing something. Please help
litAccordionFooter.Text += "<td style='width: 12.2%;font-weight: bold;'>"
+ string.Format("{0:C}", (((ds.Tables[1].Rows[0]["TOTAL_AMT"]))
== DBNull.Value ? 1
: decimal.Parse((ds.Tables[1].Rows[0]["TOTAL_AMT"]).ToString()))
/ ((int.Parse((ds.Tables[1].Rows[0]["TOTAL_QTY"]).ToString())) == 0
|| ds.Tables[1].Rows[0]["TOTAL_QTY"] == DBNull.Value ? 1
: (int.Parse((ds.Tables[1].Rows[0]["TOTAL_QTY"]).ToString())))) + "</td>";
As #JoãoKleberson says, you should validate they are not null or empty and that they have actually a int and decimal representation
int total_Amt = default(int);
decimal total_Qty = default(decimal);
if (decimal.TryParse(ds.Tables[1].Rows[0]["TOTAL_AMT"].ToString(), out total_Qty) &&
int.TryParse(ds.Tables[1].Rows[0]["TOTAL_QTY"].ToString(), out total_Amt))
{
var myString = "<td style='width: 12.2%;font-weight:bold;'>" +
string.Format("{0:C}", total_Amt / total_Qty == 0 ? 1 : total_Qty) + "</td>";
}
else
{
// The TOTAL_AMT and/or TOTAL_QTY values are not valid to convert them,
// verify they are not null and that they have the correct format
}
This way you can safety try to convert the values to the desired type, if the can't be converted the flow is going to be to the else clause
Make sure this statement:
(ds.Tables [1] .Rows [0] ["TOTAL_AMT"])
(ds.Tables [1] .Rows [0] ["TOTAL_QTY"])
It is not null or empty

Replace token's text in ANTLR

I'm trying to replace some token's text from my input program to a specific formated text. I'm using C# as output language.
Example of input:
time#1m2s
My lex grammar for that input:
fragment
DIGIT : '0'..'9'
;
CTE_DURATION
: ('T'|'t'|'TIME'|'time') '#' '-'? (DIGIT ('d'|'h'|'m'|'s'|'ms') '_'?)+
;
Output token text I'd like to get from input example:
0.0:1:2.0
That's means: 0 days, 0 hours, 1 minute, 2 seconds and 0 milliseconds.
Any advice? Thank you in advance.
Here's a way to do that (it's in Java, but shouldn't be hard to port to C#):
grammar Test;
parse
: CTE_DURATION EOF
;
CTE_DURATION
: ('T' 'IME'? | 't' 'ime'?) '#' minus='-'?
(d=DIGITS 'd')? (h=DIGITS 'h')? (m=DIGITS 'm')? (s=DIGITS 's')? (ms=DIGITS 'ms')?
{
int days = $d == null ? 0 : Integer.valueOf($d.text);
int hours = $h == null ? 0 : Integer.valueOf($h.text);
int minutes = $m == null ? 0 : Integer.valueOf($m.text);
int seconds = $s == null ? 0 : Integer.valueOf($s.text);
int mseconds = $ms == null ? 0 : Integer.valueOf($ms.text);
setText(($minus == null ? "" : "-") + days + "." + hours + ":" + minutes + ":" + seconds + "." + mseconds);
}
;
fragment DIGITS : '0'..'9'+;
Parsing the input time#1m2s results in the following parse tree:
Note that the grammar now accepts time# as well (causing it to produce 0.0:0:0.0), but you can easily produce an exception from the lexer rule in case such input is invalid.

Algorithm for finding strings that a specific Regex will match

Given a regex pattern, I'm trying to find a string that matches it. Similar to how Django reverses them, but in C#. Are there any pre-made C# libraries that do this?
Edit: Moving this project to Google code pretty soon.
Current Test Results
^abc$ > abc : pass
\Aa > a : pass
z\Z > z : pass
z\z > z : pass
z\z > z : pass
\G\(a\) > \(a\) : pass
ab\b > ab : pass
a\Bb > ab : pass
\a > : pass
[\b] > : pass
\t > \t : pass
\r > \r : pass
\v > ♂ : pass
\f > \f : pass
\n > \n : pass
\e > ← : pass
\141 > a : pass
\x61 > a : pass
\cC > ♥ : pass
\u0061 > a : pass
\\ > \\ : pass
[abc] > a : pass
[^abc] > î : pass
[a-z] > a : pass
. > p : pass
\w > W : pass
\W > ☻ : pass
\s > \n : pass
\S > b : pass
\d > 4 : pass
\D > G : pass
(a)\1 > aa : pass
(?<n>a)\k<n> > aa : pass
(?<n>a)\1 > aa : pass
(a)(?<n>b)\1\2 > abab : pass
(?<n>a)(b)\1\2 > abba : pass
(a(b))\1\2 > ababb : pass
(a(b)(c(d)))\1\2\3\4 > abcdabcdbcdd : pass
a\0 > a : pass
ab* > a : pass
ab+ > abbb : pass
ab? > a : pass
ab{2} > abb : pass
ab{2,} > abbbbbbbbb : pass
ab{2,3} > abb : pass
ab*? > abb : pass
ab+? > abbbbb : pass
ab?? > a : pass
ab{2}? > abb : pass
ab{2,}? > abbbbbbbbb : pass
ab{2,3}? > abbb : pass
/users(?:/(?<id>\d+))? > /users/77 : pass
Passed 52/52 tests.
see for example Using Regex to generate Strings rather than match them
also you can take a look at http://en.wikipedia.org/wiki/Deterministic_finite-state_machine especially at "Accept and Generate modes" section.
as others noted you will need to create a DFA from your regular expression and then generate your strings using this DFA.
to convert your regular expression to DFA, generate NFA first (see for example http://lambda.uta.edu/cse5317/spring01/notes/node9.html) and then convert NFA to DFA.
the easiest way i see is to use a parser generator program for that. i do not think django does this.
hope this helps.
"Are there any pre-made C# libraries that do this?"
NO
(I expect this will be accepted as the answer momentarily)

How can I read a IBM WebSphere MQ message of format type MQEVENT in c#

I can get the event messages from the queue. I get the message properties. I am pretty sure the MQEVENT type is in PCF format but I cannot seem to find any good documentation on how to take that message and convet it into human readable format.
AccountingToken
ApplicationIdData
ApplicationOriginData
BackoutCount 0
BackoutCount 0
CharacterSet 437
CompletionCode 0
CorrelationId System.Byte[]
DataLength 236
DataOffset 0
Encoding 546
Expiry -1
Feedback 0
Format MQEVENT
GroupId System.Byte[]
MessageFlags 0
MessageId System.Byte[]
MessageLength 236
MessageSequenceNumber 1
MessageType 8
Offset 0
OriginalLength -1
Persistence 0
Priority 0
PutApplicationName NTPMFG01
PutApplicationType 7
PutDateTime 3/19/2010 10:29:08 PM
ReasonCode 0
ReasonName MQRC_OK
ReplyToQueueManagerNameNTPMFG01
ReplyToQueueName
Report 0
TotalMessageLength 236
UserId
Version 1
And here is the message.
$ ? - ? ? ? ? D ¯ 0 MFG01 ? D - 0 MF
G.CUST.CAT ? ? # ¤ ? ? $ ? ? ? % ? ? & ?
if (myMQMessage.Format.CompareTo(MQC.MQFMT_EVENT) == 0)
I think it needs to be processed twice.
First process the PCF header with MQCFH
BuildMQCFH(new IBM.WMQ.PCF.MQCFH(myMQMessage));
public void BuildMQCFH(IBM.WMQ.PCF.MQCFH eventMessageHeader) {
int reasonForEvent = eventMessageHeader.Reason;
}
Then you MUST reset the DataOffset to 0
myMQMessage.DataOffset = 0;
Second process the PCF parameters with PCFParameter.
BuildPcfMessage(new IBM.WMQ.PCF.PCFMessage(myMQMessage));
public void BuildPcfMessage(IBM.WMQ.PCF.PCFMessage pcfMessage) {
IBM.WMQ.PCF.PCFParameter[] pcfParameters = pcfMessage.GetParameters();
afflictedQueueManager = pcfParameters[0].GetValue().ToString();
afflictedQueue = pcfParameters[1].GetValue().ToString();
}
MQMessage, PCF.PCFMessage and MQCF each do a readbyte(s) moving the offset with out resetting afterwards.

Categories

Resources