I have some decimal data coming from an external service. I need to format the data to 2 decimal places as it is represents money, but if I use the standard C format, I rounds the number:
var x = 42.999m;
var y = string.Format("{0:C}", x);
This results in y containing £43.00. How can I have it round down to £42.99?
(Note that this question is not the same)
String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
Round down for a dollar amount that has 0 to 49 cents. For example, $89.27 rounds down to $89. Round up for dollar amounts that have 50 to 99 cents. For example, $53.52 rounds up to $54.
Printf is supposed to round it. To prevent this, truncate the argument to 4 decimal places. You could sprintf() into a temp buffer for 5 decimal places and then lop off the last digit. Or, you could multiply the source number by 10,000, cast it to an int, and then back to a float and divide by 10,000.
The String. format() method is typically to format a string in Java. It can also be used for rounding a double number to 2 decimal places.
If you want to use a non-default rounding strategy, you'd need to do something like:
var x = 42.999m;
var y = string.Format("{0:C}", Math.Floor(x * 100) / 100);
Math.Floor
rounds down; however it doesn't take a number of decimal places, so you have to force the 2 decimal place behaviour.
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