iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17806

How to convert a number string from lets say 12,345,645 to 12.3M

is there an easy way to do this?

the data i get will be a string like "123,456,789"

i want to rewrite as 123.4M or 123.5M rounded, i guess ill add on the "M"

Upvotes: 0

Views: 110

Answers (2)

Hosemeyer
Hosemeyer

Reputation: 1274

The easiest way is to strip the commas, and then divide the number by 1,000,000. If you're always going to do it in millions... If you're going to want "k" and so on, then you'll need to check how long the string is.

string.strip(",")
if string.length > 3 && string.length < 7
     double = double(string)/1000;
     formattedString = string(double) + "K"     
else if string.length > 6 && string.length < 10
     double = double(string)/1000000;
     formattedString = string(double) + "M"  

Granted, that's pseudo-code so...

Upvotes: 1

cdhowie
cdhowie

Reputation: 169008

Divide it by 1,000,000 and round it to whatever precision you want, then append "M". If you tell us what programming language maybe I can offer an example.

Upvotes: 1

Related Questions