0

I'm making a calculator and the results that I'll get will be either very small or very big . So how can I change unites for a results which is where Vout is defined as a float.

Vout=1500;
self.myOutputValue.text = [NSString stringWithFormat:@"%.2f V",Vout];

this will print 1500.00 Volts what should I do to get it to print 1.5 KV

self.myOutputValue.text = [NSString stringWithFormat:@"%(  ????  ) KV",Vout];
rmaddy
  • 314,917
  • 42
  • 532
  • 579
user2988343
  • 205
  • 4
  • 8
  • 1
    self.myOutputValue.text = [NSString stringWithFormat:@"%.1f kV",Vout/1000]; ... no? either this, or I do not understand the question ... or if you want to have both, check with an if if vout is larger than 1000 before using the second version ... – Arno Saxena Nov 15 '13 at 12:29
  • yah that would be easy but I was wondering if there is somthing that will allow you to specify how many decimals on the left ? – user2988343 Nov 15 '13 at 12:39
  • Numeric formats in `stringWithFormat` will, unless directed otherwise, "expand" to handle the size of the number. Ie, you'll get "1.2", "12.3", "123.4" for 1.231, 12.312, 123.442 automatically with the `%.1f` format code. – Hot Licks Nov 15 '13 at 13:19
  • And the proper unit is `k`, not `K`. – rmaddy Nov 15 '13 at 15:23

2 Answers2

2
NSString *str = nil;
if (Vout >= 1000.0)
{
    str = [NSString stringWithFormat:@"%.1f KV",Vout/1000.0];
}
else
{
    str = [NSString stringWithFormat:@"%.2f V",Vout];
}
self.myOutputValue.text = str;
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
  • And if you need to handle more orders of magnitude, check out the logarithm function, eg. `log(1000) = 3`. Round the log to the immediately inferior multiple of 3, then you'll have your multiplier (3=K, 6=G, 9=T, ...) – Cyrille Nov 15 '13 at 12:38
  • thanks I knew that , I was wondering if there is something that will allow you to specify how many decimals on the left ? – user2988343 Nov 15 '13 at 12:39
  • can you show me an example if I will use logs ? please – user2988343 Nov 15 '13 at 12:40
2

If you like the concept of using Engineering format (i.e. 100 increments up and down) there is a nice routine in C/ObjectiveC on github: EngineeringNotationFormatter. It will let you specify the number of significant digits to show, so if you have chosen three you will get 125K, 12.5K, or 1.25K. It also lets you increment the number by the smallest possible increment up or down (useful if you couple the class to say a rotating incrementer/decrementer).

David H
  • 40,852
  • 12
  • 92
  • 138