简体   繁体   中英

C# Padding Decimal Points

I want to pad my number decimal points to 6.

So 0.0345 --> become 0.034500

0.6 --> become 0.600000

But no matter what decimal values I put in Math.Round, my code below only pads the decimal points to 5

var amount = Math.Round(0.0345, 6, MidpointRounding.AwayFromZero);
var amount1 = Math.Round(0.0345, 7, MidpointRounding.AwayFromZero);

Result: amount = 0.03450

amount1 = 0.03450

Thank you.

There are two possibilities; if amount is of type decimal , you can add zero :

decimal amount = 0.0345m;

amount += 0.000000m;

Console.Write(amount);

Outcome:

0.034500

Or represent amount in desired format:

decimal amount = 0.0345m; 

Console.Write(amount.ToString("F6"));

If amount is of type double or float then 0.034500 == 0.0345 and all you can do is to format when representing amount as a string :

double amount = 0.0345;

...

// F6 format string stands for 6 digits after the decimal point
Console.Write(amount.ToString("F6"));

Edit: In order create such kind of zero you can use

public static decimal Zero(int zeroesAfterDecimalPoint) {
  if (zeroesAfterDecimalPoint < 0 || zeroesAfterDecimalPoint > 29)
    throw new ArgumentOutOfRangeException(nameof(zeroesAfterDecimalPoint));

  int[] bits = new int[4];

  bits[3] = zeroesAfterDecimalPoint << 16;

  return new decimal(bits);
}

And so have MyRound method:

private static Decimal MyRound(Decimal value, int digits) {
  return Math.Round(value, digits, MidpointRounding.AwayFromZero) +
         Zero(digits); 
}

private static Decimal MyRound(double value, int digits) => 
  MyRound((decimal)value, digits); 

...

decimal amount = 0.0345m;

Console.WriteLine(MyRound(amount, 6));
Console.WriteLine(MyRound(0.0345, 7)); // let's provide double and 7 digits

Outcome:

0.034500
0.0345000

You can simply use format string with six decimals

decimal value = 0.6m;
Console.WriteLine("{0:0.000000}", value);
value = 0.0345m;
Console.WriteLine("{0:0.000000}", value);

// output
// 0.600000
// 0.034500

It only works this way if the incoming value is double.

            double doubleParsing = 0.0345;

            decimal amount = decimal.Parse(doubleParsing.ToString());

            amount += 0.000000m;

            var result = amount.ToString("F5");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM