GRMustache formatted numbers, or an HTML Template Engine with Number Formatting in iOS

886 Views Asked by At

I'm not sure how to best go about this. I've tried solving this my own way, but failed so far. I tried using GRMustache, only to realize that I'm trying to display floats that just look hideous in the template I'm trying to use.

Basically, I have a model that I'm trying to have output as HTML via a template. Ideally, I just put the variable names/keypaths into the template and the template just gets parsed with the actual values (pretty much) rendered in place. But, the model I'm using uses floats for all its calculations and I'd really like them rendered as comma-separated integer strings (e.g. (float)9382.233325 => "9,382").

I can't seem to find any documentation in GRMustache that covers a situation like this, but I imagine this can't be an uncommon requirement. Does anyone know how to do this with GRMustache or through some other technique?

2

There are 2 best solutions below

5
On BEST ANSWER

I'm the author of GRMustache.

There isn't, and there will never be any float formatting features in GRMustache, because there is already a perfectly well suited tool in the OS: NSNumberFormatter.

Since you're giving to GRMustache your model objects, here is my advice:

Declare a category on your model, and add a specific method for each of your formatted value:

@interface MYModel(GRMustache)
// name would match your original value property name
- (NSString *)formattedValue;
@end

In the implementation file, use a NSNumberFormatter:

@implementation MYModel(GRMustache)
- (NSString *)formattedValue
{
  // Check the NSNumberFormatter reference for initializing
  // the NSSNumberFormatter for your desired output.
  NSNumberFormatter *formatter = [NSSNumberFormatter ...]; 
  return [formatter stringFromNumber: [self value]];
}
@end

Beware creating many NSNumberFormatter instances may be costly. A good practice is to provide a shared method that returns a shared one. The code above is just a hint for the technique.

Finally, in your template, replace {{value}} tags with {{formattedValue}}.

Happy GRMustache!

0
On

GRMustache 1.12 now features a better API for number formatting: https://github.com/groue/GRMustache/blob/master/Guides/sample_code/number_formatting.md