Search code examples
iosxamarin.iosxamarinshinobi

NSNumberFormatter returning null in Xamarin.iOS + ShinobiChart


I'm trying to get a string parsed into a NSNumber that has the % character in the end where I can use the in the ShinobiChart value property of the series.

Given the following code, I'm creating the NSNumberFormatter:

var formatter = new NSNumberFormatter ();
            formatter.NumberStyle = NSNumberFormatterStyle.Percent;
            var locale = new NSLocale ("en_US");
            formatter.Locale = locale;

Now, I'll try to use the formatter to get the value for the chart slice label:

var value = formatter.NumberFromString (answer.RepliesShare.ToString () + "%");

This will give me the value 0.33... The point is, if I remove the "%" from the string, I'll get null on the value.

So, I need get a NSNumber that has the value of (i.e.) 30%(in other words, numberString+"%").

How can I get it?

To be more clear, I'm trying to achieve this:

ShinobiChart

Since ShinobiChart takes a Value of Type NSNumber and my RepliesShare is a decimal I'm trying just convert my decimal from 33.00 to 33%. The ShinobiChart don't take a string, otherwise I would have it handled. I found that NSNumber can be formatted with NSNumberFormatted so I thought I can use it since the Chart takes a number.


Solution

  • A SChartDonutSeries (and consequently SChartPieSeries) object has a LabelFormatString property. This takes a string and is used to format those labels. It has the same syntax as is used in NSNumberFormatter. Therefore, to get the behaviour you want, set the LabelFormatString after you've created the series object in your SChartDataSource subclass:

    var series = new SChartDonutSeries();
    series.LabelFormatString = "%0.2f%%";
    

    This will format numbers as 2 decimal placed with a percentage sign on the end. i.e. 25.46225.46%. Adjust the format string appropriately to get the format you desire. Remember that to get a % sign to appear you need to escape it - %%.

    Further details on creating an appropriate format string are available here: https://developer.apple.com/library/ios/documentation/cocoa/conceptual/Strings/Articles/formatSpecifiers.html