views:

92

answers:

2

I'm in the process writing a 'clever' number formatting function, which would behave this way :

1500 -> 1.5k
1517 -> 1 517
1234000 -> 1 234k
1200000 -> 1.2M

Is it possible to do this using double.toString() or another .net built-in class ?

I know it's quite easy to code, but I'd rather reuse the framework classes if the functionality already exists.

+2  A: 

I don't believe there is anything like that in .NET. Here's the key part of a PowerShell script I have to do this for me.

$prefixes = @('', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
$base = 1024;

$magnitude = [Math]::Floor([Math]::Log($_, 1024))

Write-Verbose "`$magnitude = $magnitude"

if($magnitude -eq 0)
{
 [string]$mantissa = $_
 [string]$label = 'B';
}
else
{
 [string]$mantissa = [String]::Format("{0:N}", $_ / [Math]::Pow(1024, $magnitude))

 Write-Verbose "`$mantissa = $mantissa"

 [string]$label = $prefixes[$magnitude]

 if ($IEC)
 {
  $label += "i"
 }

 $label += $unit
}


[String]::Format("{0} {1}", $mantissa, $label)

It needs to be updated to use PowerShell V2's Advanced Functions. (The parts that I didn't paste in are the parts that try to do what Advanced Functions do, and it's messy.)

Jay Bazuzi
A: 

The .NET libraries do not have anything quite like what you're looking for, but using Extension Methods you could add that functionality to them. Note that you can't override methods using extensions, only add new ones.

However, architecturally, I would be better to extend the classes you need using polymorphism and override the ToSting methods. This would avoid the overhead of extension methods, but still allow you to pass around your custom class to methods expecting a .NET number type.

Ben S
Well, I think I'll rather just use an helper method whenever I need to format my numbers. In my case, it's not often enough to justify extending the double type...
Brann