Home > Net >  Decimal numbers are turning into incorrect fractions in c#
Decimal numbers are turning into incorrect fractions in c#

Time:11-24

I am inputing this:

List<double> weightItems = new List<double> {0.23, 0.18, 0.18, 0.27, 0.14};

And when I output it like this:

objStr  = "Weights: ["   String.Join(",", weightItems)   "]\n";
return objStr;

And I am getting this as an output: Weights: [0/23,0/18,0/18,0/27,0/14]

Not sure why I am getting this. Thank you for any help

CodePudding user response:

First of all, lets modify this code a bit for it to compile:

   List<double> weightItems = new List<double> { 0.23, 0.18, 0.18, 0.27, 0.14 };
        var objStr = "Weights: ["   String.Join(",", weightItems)   "]\n";
        Console.WriteLine(objStr); 

This should return the following:

Weights: [0.23,0.18,0.18,0.27,0.14]

if this doesn't work, it is probably because you have your CultureInfo set wrong.

To fix this issue, you should include this line before you using String.Join()

 Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

if you want to replecate this issue - include the same line with "fa-Ir" instead

 Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fa-Ir");

Which will change your results to the following:

Weights: [0/23,0/18,0/18,0/27,0/14]

lidqy posted a relevant link in the comments

lidqy's link

CodePudding user response:

If you're afraid that the values are corrupted, you can easily display the values with '.' as decimal point by specifiying for example InvariantCulture (or any other culture that uses a '.' decimal separator).

//1. Specifying culture in explicit string format
List<double> weightItems = new List<double> { 0.23, 0.18, 0.18, 0.27, 0.14 };
var str = "Weights: ["   string.Join(",", weightItems.Select(d => d.ToString(CultureInfo.InvariantCulture)))   "]\n";
Console.WriteLine(str);

//2. Specifying thread culture and using it in implicit string format
List<double> weightItems = new List<double> { 0.23, 0.18, 0.18, 0.27, 0.14 };
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var str = "Weights: ["   string.Join(",", weightItems)   "]\n";    
Console.WriteLine(str);

Both outputs: "Weights: [0.23,0.18,0.18,0.27,0.14]"

  • Related