-1

Stackoverflow

This is most likely a very, very simple solution but my tired brain simply can't come up with it.

As the title suggests, I'd like to write a function that's able to convert a number like:

493205

Into a string of:

"49g 32s 5c"

What would be the most logical way of doing this?

Dennis A
  • 71
  • 7
  • Please read [the help pages](http://stackoverflow.com/help), especially ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask) and [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to create a [mcve]. – Some programmer dude Jan 31 '19 at 12:01
  • Are you having problems with the math or with building a string out of three values? – Federico klez Culloca Jan 31 '19 at 12:01
  • @FedericoklezCulloca The math seems to be the tricky part for my simple mind :-) – Dennis A Jan 31 '19 at 12:05
  • What happens if there is only four digits? – Andreas Jan 31 '19 at 12:09

1 Answers1

0

Quick one-liner, assuming $x holds the integer value:

printf('%dg %ds %dc', $x / 100 / 100, $x / 100 % 100, $x % 100);

modulo 100 gives us the last two digits, and dividing by 100 “removes” the last two digits from the number. (Technically, it gives a float, but using modulo on that again forces integer conversion first.)

04FS
  • 5,660
  • 2
  • 10
  • 21