I am using MVC 4. I've got an MVC Form two fields AmtInDollars & AmtInCents. I want to concatenate the two. Eg
var tempDollarAmt = AmtInDollars + "" + AmtInCents;
Example
Input: 100 in dollars
Input: 00 in cents
Output: 1000 // missing 1 zero due to input being 00.
Desired Output: 10000.
I realized that if the AmtInCents is between 0 and 9 it ingnores the 0. So if I type 09 the output is 9 not 09.
I have tried doing an if statement below and still no luck.
if(Products.AmtInCents < 10)
{
var tempCents = 0;
Products.AmtInCents = 00;
}
Here my class
public decimal? AmtInDollars { get; set; }
public decimal? AmtInCents { get; set; }
How can I do this?
you should use string.format to force padding when formating number
var tempDollarAmt = String.Format("{0}.{1:00}",AmtInDollars ,AmtInCents);
//Input: 100 in dollars
int dollars = 100;
//Input: 00 in cents
int cents = 0;
//OutPut: 1000 // missing 1 zero due to input being 00.
int output = dollars * 100 + cents;
Related
ive just started some classes on c# and have been given an assignment with the following rules:
Prompt the user to enter an amount of dollars and cents. For example 1.18
- Display the number of quarters, dimes, nickels, and pennies to make that amount
Example If they entered 2.16 it should say:
8 quarters, 1 dimes, 1 nickels, 1 pennies
the problem that i run into is that this only seems to work if they type the money value as a whole. so if they wanted to type $1.18 they would type 118 and it would work just fine, but as soon as they type 1.18 it crashes. another example would be if they were to type 765 for $7.65 it would work fine, however if they type it correctly as 7.65 it would fail. sorry for the lame question, im super new, thanks for the help!
int totalCash;
Console.WriteLine("input money");
string moneyString = Console.ReadLine();
totalCash = int.Parse(moneyString);
int quarter = totalCash / 25;
totalCash %= 25;
int dime = totalCash / 10;
totalCash %= 10;
int nickel = totalCash / 5;
totalCash %= 5;
int penny = totalCash / 1;
totalCash %= 1;
Console.WriteLine("{0} quarters, {1} dimes, {2} nickels, {3} pennies", quarter, dime, nickel, penny);
```
There are lots of ways get the result but this the best approach I ever tried :
public static string ConvertMoneyIntoCoins(double money)
{
int cents = (int)(Math.Round(money, 2) * 100);
var coins = new[] {
new { Name = "Quarters", Value = 25 }, new { Name = "Dimes", Value = 10 },
new { Name = "Nickels", Value = 5 }, new { Name = "Pennies", Value = 1 }
};
var changes = coins.Select(coin => new { Amt = Math.DivRem(cents, coin.Value, out cents), Coin = coin }).Where(x => x.Amt != 0).ToList();
var strBld = new StringBuilder();
foreach (var change in changes)
{
strBld.Append(change.Amt + " " + change.Coin.Name + ", ");
}
return strBld.ToString();
}
It's working when you enter whole number should be the clue you pay attention to. If you assume the whole number is dollars, you can not mod by a whole number. All of your divisors are a factor of 100 too big. When you do that, you'll notice that you have the wrong data type as well. Note that i disagree with using tryparse when debugging as it eats errors. You should be running it in debug mode and then you would get an actual stack trace and a line it crashes at.
I have a website that calculates the price of bus tickets. Currently the price is rounded to the nearest 10, but now I want the calculated price to be rounded to the nearest number ending in 9.
EDIT: Added new examples answering question from the comments.
Examples:
770 to 774 should be rounded to 769
775 to 784 should be rounded to 779
785 to 790 should be rounded to 789
Does anybody have any tips on how I can solve my problem using c#?
Round to the nearest 10 and then subtract 1.
In c#, you can do it like this :
double val = 444.3;
double step1 = val/10; // 44.43
double step2 = Math.Round(step1, MidpointRounding.AwayFromZero); // 44
int step3 = (int)step2 * 10; // 440
int rndVal = step3 - 1; // rndVal == 439
or the shortest version :
double val = 444.3;
int rndVal = (int)(Math.Round(val/10, MidpointRounding.AwayFromZero)*10)-1;
Add 1, round to nearest 10 and then subtract 1.
The function below will do the job.
public static int RoundTo9(double value)
{
return (int)(value/10.0 + 0.5) * 10 - 1;
}
int number=65;
// Console.WriteLine(number);
int lastNumber=number%10;
//Console.WriteLine(lastNumber);
if(lastNumber<5)
{
number-=lastNumber;
number--;
Console.WriteLine(number);
}
else
{
var addNumber=10-lastNumber;
number+=addNumber;
number--;
Console.WriteLine(number);
}
I have a list of list of string in order to group the string with the number of '1' like string = "00000" belongs to the first group and string = "00001" belongs to the second group. ALl String are equal length. Now I compare the first group to the second group and second group to third group and soon...like in the Image. The First element in the first group is compared to all elements of the second group. Until every string are compared. Is There a way to speed up the performance of my program? So I can Achieved 32000 string with 15 Length.
Edit
Sorry for the past post.After reading it i realize I was to dumb asking like that.
The goal of the program was a simplifier. Based on the Quine–McCluskey algorithm
Consider
000
001
010
011
100
101
110
111
I group them by number of 1
000
001
010
100
011
101
110
111
Then I compare each string from the group to the next group
group 1
000
group 2
001
010
100
group 3
011
101
110
group1 -> group2
------------------
000 -> 001 = 00-
000 -> 010 = 0-0
000 -> 100 = -00
------------------
group2 ->group3
--------------------
001 -> 011 = 0-1
001 -> 101 = -01
001 -> 110 = no output
010 -> 011 = 01-
010 -> 101 = no output
010 -> 110 = -10
100 -> 011 = no output
100 -> 101 = 10-
100 -> 110 = 1-0
---------------------
etc.
then group the output again by number of 1 and compare them again until no strings can be compared.
I need to achieve a 15 variable but it take for ever for the program to finish.Any Idea how to speed it up. I was testing it on threading but just a little improvement.
Number of Strings: 2048 Length of variable: 11 Time: 10 minutes
Need to Achieved
Number of Strings: 32767 Length of variable: 15 Time: cannot be achieved
List<List<string>> ImplicantsByOneFinal = new List<List<string>>();
List<List<string>> TermsByOne = new List<List<string>>();
is there a way or algorithm to improve this code. it becomes slower on 11 to 15 variables.
bool CombineAndGroup(List<List<string>> ImplicantsByOne)
{
TermsByOne = new List<List<string>>();
int combined = 0;
for (int i = 0; i < ImplicantsByOne.Count - 1; i++)
{
List<string> termsGrouped = new List<string>();
for (int j = 0; j < ImplicantsByOne[i].Count; j++)
{
int combination = 0;
int num1 = Convert.ToInt32((ImplicantsByOne[i][j]).Replace('-','0'), 2);
for (int k = 0; k < ImplicantsByOne[i + 1].Count; k++)
{
int num2 = Convert.ToInt32((ImplicantsByOne[i + 1][k]).Replace('-', '0'), 2);
int num3 = num2 - num1;
double num4 = Math.Log((double)num3, (double)2);
if (((num4 % 1) == 0) && (num3 > 0) && (Esum(ImplicantsByOne[i][j]) == Esum(ImplicantsByOne[i + 1][k])))
{
string combinedMinterm = CompareString(ImplicantsByOne[i][j], ImplicantsByOne[i + 1][k]);
if (!termsGrouped.Contains(combinedMinterm))
{
termsGrouped.Add(combinedMinterm);
}
}
}
}
if (termsGrouped.Count > 0)
{
combined += termsGrouped.Count;
}
TermsByOne.Add(termsGrouped);
}
return (combined > 0) ? true : false;
}
private int Esum(String binCode)
{
binCode = binCode.Replace('1','0');
binCode = binCode.Replace('-', '1');
int esum = Convert.ToInt32(binCode, 2);
return esum;
}
//Purpose of CompareString is to compare two string and change the unique char to '-'
//like 000 and 001 = 00-
private string CompareString(string str1, string str2)
{
if (str1 == str2)
{
CountCompareStringLoops++;
return str1;
}
else
{
if (str1.Length == 1)
{
return "-";
}
int halflength = str1.Length / 2;
return CompareString(str1.Substring(0, halflength), str2.Substring(0, halflength)) + CompareString(str1.Substring(halflength), str2.Substring(halflength));
}
}
Main Program
MintermsByOne = Loaded with string 000 001 and so on
CombineAndGroup(MintermsByOne);
ImplicantsByOneFinal = TermsByOne;
while (CombineAndGroup(TermsByOne))
{
ImplicantsByOneFinal = TermsByOne;
}
Output ImplicantsByOneFinal
It's not really clear what you're trying to achieve, to be honest... your description doesn't match your code. (Your code never mentions the character '1', for example. The fact that you never use the result of calling CompareString is suspicious too.) LINQ should make implementing your description of "group the string with the number of '1' " easy and efficient:
var grouped = strings.GroupBy(x => x.Count(c => c == '1'));
That will only count the number of '1' characters in each string once. You never need to compare any string with another one.
If this isn't what you're actually trying to do, you need to clarify what your actual aim is.
I don't know how to write C#, but I want to help. So my code is given in Java.
1. I think == is an O(n) operation, your CompareString may be O(nlgn) where n = str1.Length. Use a simpler and faster O(n) way and see if the time decreases:
private String CompareString(String str1, String str2) {
StringBuilder sb = new StringBuilder(str1.length());
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) == str2.charAt(i))
sb.append(str1.charAt(i));
else
sb.append('-');
}
return sb.toString();
}
2. Well, I found out there are a lot of ToInt32. Calculate the result of all strings in ImplicantsByOne at once and use it later. So does Esum.
3. To check if num3 is a power of two:
private boolean isPowerOfTwo(int x) {
return (x > 0 && (x & (x - 1)) == 0);
}
I've got this - possibly trivial - loop/combinations problem similar to binary combinations. I don't know how to approach it efficiently. Consider this scenario, I need unique loop to pass through all these combinations in a sequence:
Round ABC
01. 000 <- values of A=0, B=0, C=0
02. 001
03. 010
04. 011
05. 100
06. 101
07. 110
08. 111
09. 002
10. 012
11. 102
12. 112
13. 020
14. 021
15. 120
16. 121 <- values of A=1, B=2, C=1
17. 022
18. 122
19. 220
20. 221
21. 222
Except there are 12 letters (A-L), and also the "bit" size is not just 0,1 or 2 but any integer number (from 0 possibly up-to 1000 or 1024, not to make it crazy). I know it's a huge load of combinations, but I'll just scrap just top few that also fulfill my other conditions. So no need to worry about computational madness.
Disclaimer: The order has to be exactly as shown above. NOT a multiple FOR loops going first 0-1024 for C, then B.
Thanks in advance, I just can't seem to find the way to "algorithm it".
Update: Added whole sequence for combinations of ABC/012
regards,
Kate
Explanation:
I've encountered this problem when trying to tackle problem of analyzing sum of money for its combination of coins/notes:
For example $5001 to find out x optimal combinations.
10x $500 + 1x $1
50x $100 + 1x $1
..
Now letters (A,B,C..) correspond to a number of possible values of banknotes or coins ($1, $5,.. $100). While base correspond to a number of pieces of that banknotes/coins (for example $5001/$5000 = 1piece max.)
if I guess your sequence right, you will have it easier to generate it recursively
here an approach in Java, which should generate a sequence that matches your scenario.
I hope it helps you (maybe I add more explanation later):
public static void init() {
// define constants
final int length = 3;
final char maxValue = '3';
// define buffer
final char[] array = new char[length]; java.util.Arrays.fill(array, '0');
final boolean[] alreadySet = new boolean[length]; java.util.Arrays.fill(alreadySet, false);
// fill first digit, then let the recursion take place
for(char c = '1'; c <= (char)(maxValue); c++) {
// iterate from lowest to highest digit
for(int i = array.length-1; i >= 0; i--) {
// set value
array[i] = c;
alreadySet[i] = true;
// print value
System.out.println(new String(array));
// call recursion
recursive(array, c, i, alreadySet, length);
// unset value
alreadySet[i] = false;
array[i] = '0';
}
}
}
public static void recursive(char[] array, char lastValue, int lastIndex, boolean[] alreadySet, int leftToSet) {
// if we didn't set all digits
if(leftToSet > 0) {
// iterate from lowest to highest digit
for(int i = array.length-1; i >= 0; i--) {
// missing all digits already set
if(!alreadySet[i]) {
// count from 1 to lastValue-1
for(char c = '1'; c < lastValue; c++) {
// set value
array[i] = c;
alreadySet[i] = true;
// print value
System.out.println(new String(array));
// call recursion
recursive(array, c, i, alreadySet, leftToSet-1);
// unset value
alreadySet[i] = false;
array[i] = '0';
}
}
}
char c = lastValue;
// iterate from lowest to highest digit
for(int i = array.length-1; i > lastIndex; i--) {
// missing all digits already set
if(!alreadySet[i]) {
// set value
array[i] = c;
alreadySet[i] = true;
// print value
System.out.println(new String(array));
// call recursion
recursive(array, c, i, alreadySet, leftToSet-1);
// unset value
alreadySet[i] = false;
array[i] = '0';
}
}
}
}
A rough sketch in pseudo C#/Java:
Mapping A-L to indexes 0-11
const int[] maxvalues = { define max values for each var }
int[] counters = { initialize with 0s }
while (true)
{
for(i in 11..0)
{
counters[i]++;
if (counters[i] < maxvalues[i])
break; // for
counters[i] = 0;
}
if (counters[0] == maxvalues[0])
break; // while
print(counters.ToDisplayString());
}
(Just noted that the second sequence does not match the first sequence in OP. If OP is correct, I guess I didn't "get" the sequence)
The sequence of numbers you've described can be enumerated by counting upward from 0 in a base representation of numbers one higher than the amount of "letters" used to create your individual sequences.
One simple way to do this is to use a radix converter from base 10 which will act on a variable being incremented in a single loop from 0 to the maximum number of combinations you are looking to achieve.
Here is an implementation:
void Main()
{
for(int i=0; i< 50; i++){
Console.Write(convert(5,i));
Console.Write("\n");
}
}
string convert(int N, int M){
Stack<int> stack = new Stack<int>();
while (M >= N){
stack.Push(M %N);
M = M / N;
}
string str = M.ToString();
while(stack.Count() > 0)
str = str + stack.Pop().ToString();
return str;
}
Starting output:
0
1
2
3
4
10
11
12
13
14
20
21
22
23
24
30
31
32
33
34
40
41
42
43
44
100
101
102
103
104
I'm making a table with Decimal, Binary, Octal and Hexadecimal columns. I wrote methods that display each of these types from a low number to a high number. My question is how do I display these methods side by side so they line up in the appropriate column?
I tried using the following, but it contains "invalid arguments":
Console.WriteLine("{0}\t{1}\t...", generate.buildDecimal(), generate.buildBinary(),...)
Here is my code:
using System;
public class Converter
{
int decimal0;
int decimal1;
int decimal2;
int decimal3;
int bottomLimit;
int topLimit;
// prompt user for range of numbers to display
public void PromptUser()
{
Console.Write("Enter bottom limit: ");
bottomLimit = Convert.ToInt32(Console.ReadLine());
decimal0 = bottomLimit;
decimal1 = bottomLimit;
decimal2 = bottomLimit;
decimal3 = bottomLimit;
Console.Write("Enter top limit: ");
topLimit = Convert.ToInt32(Console.ReadLine());
}
// display decimal values in range
public void buildDecimal()
{
while (decimal0 <= topLimit)
{
Console.WriteLine(decimal0);
decimal0++;
}
}
// display binary values in range
public void buildBinary()
{
while (decimal1 <= topLimit)
{
string binary = Convert.ToString(decimal1, 2);
Console.WriteLine(binary);
decimal1++;
}
}
// display octal values in range
public void buildOctal()
{
while (decimal2 <= topLimit)
{
string octal = Convert.ToString(decimal2, 8);
Console.WriteLine(octal);
decimal2++;
}
}
// display hexadecimal values in range
public void buildHex()
{
while (decimal3 <= topLimit)
{
string hex = Convert.ToString(decimal3, 16);
Console.WriteLine(hex);
decimal3++;
}
}
// call methods
public static void Main(string[] args)
{
Converter generate = new Converter();
generate.PromptUser();
Console.WriteLine("Decimal Binary Octal Hexadecimal");
generate.buildDecimal();
generate.buildBinary();
generate.buildOctal();
generate.buildHex();
}
}
As of right now, the program returns something like this:
Enter bottom limit: 1
Enter top limit: 10
Decimal Binary Octal Hexadecimal
1
2
3
4
5
6
7
8
9
10
1
10
11
100
101
110
111
1000
1001
1010
1
2
3
4
5
6
7
10
11
12
1
2
3
4
5
6
7
8
9
a
If you can't tell from my code, I'm a beginner, so please try not to go too far over my head. I'm actually supposed to put all of the methods in a separate class, but I couldn't figure out how to call the methods. I tried to call them in Converter with something like:
Converter callMethod = new Converter();
callMethod.buildDecimal();
But it didn't know what I was referring to.
Since the bottom limit/top limit are always the same you could just use a single method.
see below.
public void BuildNumbers()
{
while (decimal1 <= topLimit)
{
string binary = Convert.ToString(decimal1, 2);
string dec = Convert.ToString(decimal1);
string oct = Convert.ToString(decimal1, 8);
string hex = Convert.ToString(decimal1, 16);
Console.Write(binary);
Console.Write('\t');
Console.Write(dec);
Console.Write('\t');
Console.Write(oct);
Console.Write('\t');
Console.Write(hex);
Console.WriteLine();
decimal1++;
}
}