Home > Software design >  Formatting a double within an interpolation
Formatting a double within an interpolation

Time:10-31

I have an interpolation where I need to format the variable to 2 places. The variable here is 'difference'

double difference = moneyLeft - trip;
Console.WriteLine($"Not enough money! {difference} needed.") ;

I have tried putting {0:f2} but doesn't seem to work. Currently it gives me a number like 418.2, where I need it to be 418.20. How can I fix it?

CodePudding user response:

You can use the following code

double res = moneyLeft - trip;
string difference = String.Format("{0:0.00}", res); // say difference: 418.2
Console.WriteLine($"Not enough money! {difference} needed."); // Output: 418.20

CodePudding user response:

There are two parts of the token syntax ({ }), the "before the colon", and the "after the colon".

When you're inside an interpolated string, the "before the colon" part is treated as code. That means if you use a variable name, it evaluates the value stored in that variable. If you give it a numeric literal, such as 0, it uses the value 0.

var input = 3.21;
string a = $"{input}"; // 3.21
string b = $"{0}"; // 0

0 In this case doesn't mean the "first positional argument after the template", such as is used in string.Format.

You already figured out that you should use f2 after the colon to get two decimal spots, but remember you can't use 0 before the colon, or else the value you'll be formatting is literally the number zero.

var input = 3.21267674;

// your first attempt
string a = $"{input}"; // 3.21267674

// your second attempt
string b = $"{0:f2}"; // 0.00

// the correct way
string c = $"{input:f2}"; // 3.21
  • Related