0

I am getting a string as 160. I want to display it as a number by dividing it by 10, i.e,. as 16.0. But it should be a float value. My code is working fine for values like 157, where it is getting converted to 15.7 and getting displayed. But in case of whole numbers like 160,170,140 last zero is getting lost and it is being displayed as 16,17 and 14. Other searches showed that it can be done by formatting the strings. But I want the final result to be in a float format with precision (as 16.0 exactly). How can it be done?

Below code is working fine for numbers other than whole numbers. Value is of float type. Result is of string type.

Value = Convert.ToInt16(Result) / 10.0f;
barbsan
  • 3,418
  • 11
  • 21
  • 28
divya
  • 1

2 Answers2

1

Convert it to float, then use ToString("N1")

string myValue = "160";
string myString = (float.Parse(myValue) / 10.0f).ToString("N1");

https://dotnetfiddle.net/ySWKG3

Renan Araújo
  • 3,533
  • 11
  • 39
  • 49
0
Value = Convert.ToInt16(Result) / 10.0f;

is ok but you likely want to:

string displayedVal = (float.Parse(Result) / 10.0f).ToString("####0.0");

you have a string result... the float you already had was precise enough but the .0 was truncated from the output. if you do not want the end to be a string just stop at:

float fVal = float.Parse(Result) / 10.0f;
NappingRabbit
  • 1,888
  • 1
  • 13
  • 18