skip to Main Content

I have a file with various characters and either words as well as numbers. These numbers can be integers like a 1 or 12 (as an example) or they have a comma and countless digits after the comma.
for example:

",{"n":"Box","p":[-4.0,4.0,0.0],"r":[270.0,0.0,0.0],"s":[1.0,1.000006,1.000006],"c":[0.448529363,0.4280135,0.412251264],"m":"wood_14"}"

The file is read with File.ReadAllText and then passed to NewtonsoftJson via JsonProperty accordingly
for example:

[JsonProperty("s")]
public double[] Scale
{
    get;
    set;
}

For example, with Scale, I want to limit the decimal places to a maximum of 5 digits.
Is this possible and if so, how?
I have been trying for days with different things, but nothing has worked yet.

My idea was to intervene in the string I build first before passing that to Json there. But unfortunately this does not work. I tried it with regular expression like Notepadd++ makes for example.

(edit)

2

Answers


  1. double.ToString() will do it.

    const double d = 0.123456789;
    string s = d.ToString("G5");
    Console.WriteLine(s);
    

    That outputs 0.12346, showing that it rounds the 5 to 6.

    Documentation for Double.ToString shows much more detailed examples of how to format numbers.

    The number format (i.e. decimal separator) is culture-specific. If you want to use the current culture, then the above will work. If you always want a comma as the decimal separator, you’ll have to call the overload that accepts an IFormatProvider for the specific culture.

    Login or Signup to reply.
  2. I don’t know if you want it to serialize or deserialize. So I made code for both cases. You have to leave one variant or another

    public class a
    {
        private double[] val;
        
        [JsonProperty("s")]
        public double[] Scale
        {
    
            get {    return val;
                     // or
                     val?.Select(v => Math.Round(v, 5)).ToArray();  }
            set { 
                     val=value;
                     //or
                    val = value?.Select(v => Math.Round(v, 5)).ToArray(); 
            }
        }
    }
    

    if you want it in many properties you can make it as a function

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search