sver
sver

Reputation: 942

Set value for Progress bar in xamarin

I have value of a field coming from server lfrom 1 to 100 which is to show progress of that field. But I checked that we can provide value to progress bar from 0 to1. How can i convert this. I did something like this but didn't work

Int Field = 12; 
Decimal d = Field / 100; 
Decimal dc = Math.Round(d,1); //to round to one decimal place 
return dc;

This is returning 0. I tried this too:

double d = (double)(Progress / 100);
double dc = Math.Round(d, 1); 
return dc;

This is also returning 0.

Upvotes: 0

Views: 750

Answers (2)

nevermore
nevermore

Reputation: 15816

Turns out "/" operator doesn't work in C#

NO, "/" operator do work in C#.

You get a zero because Field / 100; is int/int, the result is 0;

Progress / 100 is the same, int/int get 0;

To make your code work. You can define the field as type Decimal :

    Decimal Field = 12;
    Decimal d = Field / 100;
    Decimal dc = Math.Round(d, 1);

Or cast the 100 to Decimal:

   int Field = 12;
   Decimal d = Field /(Decimal)100;
   Decimal dc = Math.Round(d, 1);

You can see detailed answer in these two threads: why-does-integer-division-in-c-sharp-return-an-integer-and-not-a-float

and

how-can-i-divide-two-integers-to-get-a-double

Upvotes: 1

GiampaoloGabba
GiampaoloGabba

Reputation: 1458

if you want maximum precision, you can convert an old range of values in a new range maintaining the ratio with this formula:

var OldRange = (OldMax - OldMin);  
var NewRange = (NewMax - NewMin);  
//i'm using round here has you requested, but its better to dont use it to achieve best results
var NewValue = Math.Round(((OldValue - OldMin) * NewRange) / OldRange) + NewMin, 1);

In your case, taking for example the number 12, this will be:

var OldRange = 99 //(100 - 1);  
var NewRange = 1 //(1 - 0);  
var NewValue = Math.Round(((12 - 1) * NewRange) / OldRange) + 0, 1);

Concluding the number 12 in the old range is 0.1 in the new range.

Or if you dont care that the old range starts from 1 and the new from 0, you can just divide by 100 and round the value:

Int field = 12; 
Decimal d = field / 100; 
Decimal dc = Math.Round(d,1); //to round to one decimal place 
return dc;

Please note that in c# the divide operator is / and not % (wich is the modulus)

Upvotes: 2

Related Questions