I have the Viewmodel:
public class PartnerSearchResultVM
{
public int Id { get; set; }
public string Name { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public double Distance { get; set; }
public string Classification { get; set; }
}
I get the distance in meters from the database like this: 2354,58764478263 m
I would like to present 2.35 km
How change the Viewmodel to make the convertion there (if it's the best place to do it)
I'd add a read-only property to your model.
public double Kilometers { get { return this.Distance / 1000; } }
If you want a formatted string back I'd create a second readonly property.
public string KilometerDisplay {
get {
return String.Format("{0:0.00}km", this.Kilometers);
}
}
Although, depending on your use case, a generalized format function might be appropriate. Perhaps as an extension method:
[Extension]
public string FormatDistance(this double distance) {
return distance.FormatDistance("");
}
[Extension]
public string FormatDistance(this double distance, string unitString) {
return return String.Format("{0:0.00}{1}", distance, unitString);
}
// for meters: result.Distance.FormatDistance("m");
// for kilometers: result.Kilometers.FormatDistance("km");
Then add some XML documentation to the Distance property explaining that it is in meters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With