Click here to Skip to main content
15,905,616 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,
I have a Problem in displaying numeric(decimal) Values.

if user enters numeric Value as 12.00 it should display as 12.00,
if user enters numeric Value as 12.0 it should display as 12.0,
i have stored these value as Float datatype,i have to perform some calculation based on these values.

i know 12,12.0 12.00 are same, but i need to display according to User Input.

What I have tried:

i tried using
C#
(Convert.ToDecimal(12.0)).ToString("#.##");

but it gives me o/p as 12
C#
(Convert.ToDecimal(12.0)).ToString("F");

o/p as 12.00
Posted
Updated 10-Apr-16 21:34pm
v3
Comments
Tomas Takac 11-Apr-16 2:30am    
I guess you don't really have a choice here. You need to store both, the text entered by the user so you can show it back in the same format, and the float value to do the calculations.

Floats do not store a precision, or trailing zeros: it's just a number, in the same way that an integer doesn't store leading zeros: you can enter 1234 and it's the same number as 00000000001234
If you want to display data in the same precision that the user entered it, you would need to store information about the precision with the data - I'd suggest creating a new class called PrecisionFloat that holds both the floating point value and the number of decimal places, and uses that info to override ToString.
But...what happens if the user enters two values 123.00 and 123.0000, then you add them together? What happens to the precision? Should the result be two decimal or four? What if you multiply them? 2, 4, 6, or 8?
I suspect that you are trying too hard: use precision that is relevant to the task in hand, rather than the user input!
 
Share this answer
 
You should not be using float, you should be using decimal (C# Reference)[^] to store your values.
 
Share this answer
 
You cannot do it without some extra programming.

You could try using 0.0#, that will show one decimal minimum (i.e 12.0, but will show 12.0 for 12.00 too. But it will show correctly 12.1 and 12.11 as 12.1 and 12.11...it is just for trailing zeroes that you may have trouble with.

What you could do is parse the initial input and along with the number save the format in the form #0.0# where number of zeroes behind the decimal point is the result of your initial parsing of the user input
 
Share this answer
 
Quote:
f user enters numeric Value as 12.00 it should display as 12.00,
if user enters numeric Value as 12.0 it should display as 12.0,

In order to keep user input, you have to store the input as a string and to convert to float for calculation.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900