Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent rounding of decimals when using currency string format

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)

like image 839
Nicola Steadman Avatar asked May 18 '11 09:05

Nicola Steadman


People also ask

How do you round a string to two decimal places?

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 %.

How do you round currency?

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.

How do I stop printf from rounding?

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.

Does string format round Java?

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.


1 Answers

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.

like image 81
RichardW1001 Avatar answered Oct 01 '22 15:10

RichardW1001