I have the following problem: After I add a string to my number the second digit after the point disappears like this
var needed_product = sets * (2 * price_bananas) +
sets * (4 * price_eggs) +
sets * (0.2 * price_berries);
var difference = Math.Abs(needed_product - amount_cash);
if (amount_cash>=needed_product)
{
Console.Write("Ivancho has enough money - it would cost " + "{0:F2}",
needed_product + "lv.");
}
The output is 37,4 when it should be 37,40 with one more digit after the comma. How do I fix this problem? When I print it without adding the last piece of string the output of the integer is correct.
You are incorrectly formatting your string.
Console.Write
takes a string argument, and then optionaly some arguments afterwards to pass into the string.
In your example code, your string is
"Ivancho has enough money - it would cost " + "{0:F2}"
and then the argument you pass into that string is
needed_product + "lv."
needed_product
is added to "lv.", and in the process being converted into a string without your custom parameters. This means that {0:F2}
is converted into a string and ignores the F2 modifier, giving
"Ivancho has enough money - it would cost 37.4 lv."
Instead, use
Console.Write("Ivancho has enough money - it would cost {0:F2} lv.", needed_product);
You could use a custom format within a toString() call.
double value = 37.4;
Console.WriteLine(value.ToString("0.00"));
The problem is that you are concatenating the decimal value with a string, before it's being formatted.
In other words, your current code is functionally equivalent to:
var temp = needed_product + "lv."; // this gets formatted using default formatting
Console.Write("Ivancho has enough money - it would cost {0:F2}", temp);
To fix it, you should simply insert units into the actual format string:
Console.Write("Ivancho has enough money - it would cost {0:F2} lv", needed_product);
If you run the following, fixed code:
void Main()
{
var sets=6;
var price_bananas=0.88;
var price_eggs=1.10;
var price_berries=0.37;
var amount_cash=40;
var needed_product = sets * (2 * price_bananas) + sets * (4 * price_eggs) + sets * (0.2 * price_berries);
var difference = Math.Abs(needed_product - amount_cash);
if (amount_cash >= needed_product)
{
Console.Write(
"Ivancho has enough money - it would cost "
+ "{0:F2} lv.", needed_product);
}
}
It produces the correct output:
Ivancho has enough money - it would cost 37,40 lv.
Explanation:
The other way you were trying first converts the number to a string internally (by using the equivalent of the .ToString()
method), and then later applies the formatting {0:F2}
which became useless because the number is already a string, formatted by default options.
To avoid this, build up the complete formatting string, then add the parameters without modification (as shown in the code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With