Home > other >  I want to use string formatting to limit decimals and right align numbers. But I don't know how
I want to use string formatting to limit decimals and right align numbers. But I don't know how

Time:01-27

I apologize to those who find it difficult to answer due to my awkward sentences.

//Numbers are entered using the keyboard
double num1 = 10.234256; 
double num2 = 593.242523333;
double num3 = -32423.412929333425;

Console.WriteLine($"{num1:f3, 25}");
Console.WriteLine($"{num2:f3, 25}");
Console.WriteLine($"{num3:f3, 25}");

I wrote the code like above. I thought the decimal point would be limited and the numbers would be aligned 25 spaces to the right, but that didn't happen. I need to use string interpolation, and also don't want to use a rounding function.

I tried using these codes String.Format, {0:f3, 25} to solve this problem. But all failed.

Without using System.Linq, please use the code {0:f3} to limit the decimal point to 3 digits and tell me how to right or left align the number.

CodePudding user response:

The alignment component should precede the format string component:

Console.WriteLine($"{num1,25:f3}");

Here is the syntax:

{index[,alignment][:formatString]}
  • Related