Converting int to dchar?

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 31 14:50:15 PDT 2016


On 07/31/2016 11:31 PM, Darren wrote:
> If I try and cast it to dchar, I get messed up output,

Because it gives you a dchar with the numeric value 5 which is some 
control character.

> and I'm not sure
> how to use toChars (if that can accomplish this).

     value = i.toChars.front;

toChars converts the number to a range of chars. front takes the first 
of them.

Similarly, you could also convert to a (d)string and take the first 
character:

     value = i.to!dstring[0];

Or if you want to appear clever, add i to '0':

     value = '0' + i;

I'd generally prefer toChars.front here. to!dstring[0] makes an 
allocation you don't need, and '0' + i is more obscure and bug-prone.


More information about the Digitalmars-d-learn mailing list