Mr Lister
Mr Lister

Reputation: 46559

String.Format anomaly

I'm probably a great big idiot for not seeing something extremely obvious, but I don't know what I can check now.

The problem is this. If I have this code

decimal d = 45550M;
string s = string.Format("{0}", d);

the result sometimes is "45550,00" instead of "45550". And I don't know what causes this.

What can I check? What can cause String.Format to not always behave the same?

Upvotes: 2

Views: 150

Answers (3)

dtb
dtb

Reputation: 217273

A decimal value has a certain scaling factor. Depending on the operations you perform on a decimal value, the scaling factor can change.

A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value.

Unless you specify a number of decimal places, the number of decimal places defaults to match the scaling factor of the decimal value.

The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeroes can be revealed by the ToString method if an appropriate format string is applied.

Example:

var x = 100m;
var y = x * 1.00m;

string s1 = string.Format("{0}", x); // "100"
string s2 = string.Format("{0}", y); // "100.00"

Upvotes: 5

Alex
Alex

Reputation: 23300

string.Format("{0:0}", d); should always output 0 decimals ("45550")

Upvotes: 2

Ivan Zlatev
Ivan Zlatev

Reputation: 13196

The result will vary from machine to machine, because you are not specifying an explicit culture to use for the formatting, so the runtime will use the current thread culture, which will really be the one configured on the machine.

Upvotes: 3

Related Questions