Home > Software engineering >  Adding specified numbers of zeros after the floating point to a decimal type
Adding specified numbers of zeros after the floating point to a decimal type

Time:01-24

Is there any way I can add a specified number of zeros after the significant part of the number after the floating point to a decimal type without using string.Format() to avoid performance issues?

For example say I have the number:

var number = 5.023m;

And I want to add 5 zeros (this can vary) after the number so it becomes

number = 5.02300000;

CodePudding user response:

How about using the String.PadRight()?

var number = 5.023m;
var s = number.ToString(".###");
string text = s.PadRight(s.Length 5,'0');

CodePudding user response:

You can convert the number to string, add it zeros and then convert it back to decimal, here is an example:

var number = 5.023m;
var numberAsString=number.ToString();
int n = 5; //add n zeros, e.g n=5
for (int i = 0; i < n; i  )
    numberAsString  = '0';
number = decimal.Parse(numberAsString);
Console.WriteLine(number);// output:  5.02300000
  • Related