1

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?

Chris Snow
  • 23,813
  • 35
  • 144
  • 309
ceci
  • 429
  • 1
  • 7
  • 22
  • This code looks like c#. Is this c#? – user3437460 Sep 21 '15 at 16:52
  • you want "zero padding" – ddavison Sep 21 '15 at 16:54
  • Try this.. `var tempDollarAmt = AmtInDollars.ToString() + AmtInCents.ToString();` – Amnesh Goel Sep 21 '15 at 16:59
  • 1
    possible duplicate of [c# - How do I round a decimal value to 2 decimal places (for output on a page)](http://stackoverflow.com/questions/164926/c-sharp-how-do-i-round-a-decimal-value-to-2-decimal-places-for-output-on-a-pa) – w.b Sep 21 '15 at 17:05
  • Why not directly using `string` type? what is the reason and why it has to be `decimal?`? – M.kazem Akhgary Sep 21 '15 at 17:09
  • You should not use the names `AmtInDollars` and `AmountInCents`. I would assume that both variables would hold the entire amount rather than each holding a portion of the total. I would recommend that you use `Dollars` and `Cents` since the actual amount is them combined. – Ryan Gates Sep 21 '15 at 18:15

2 Answers2

3

you should use string.format to force padding when formating number

var tempDollarAmt = String.Format("{0}.{1:00}",AmtInDollars ,AmtInCents); 
CaldasGSM
  • 3,032
  • 16
  • 26
  • I get an error **Input string was not in a correct format.** when trying to save it. – ceci Sep 22 '15 at 13:31
  • I should've mention before the error above I got **cannot implicitly convert string to decimal**. Then I did `Convert.ToInt32(tempDollarAmt)` and got the **Input string was not in a correct format.** error. – ceci Sep 22 '15 at 13:36
0
//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;
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37