Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 658
Mr Lister Avatar asked Nov 16 '25 14:11

Mr Lister


2 Answers

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"
like image 117
dtb Avatar answered Nov 19 '25 05:11

dtb


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.

like image 27
Ivan Zlatev Avatar answered Nov 19 '25 05:11

Ivan Zlatev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!