Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including zeros in front of an integer [duplicate]

Tags:

swift

I have a number that I want to represent the player's score in a SpriteKit game I'm developing.

var score = 000000000

I then create an SKLabelNode with that as part of the string ("SCORE: \(score)") . So when I run it, it should currently say: "SCORE: 000000000".

However, it actually says: "SCORE: 0".

I'm making a 2D-platformer in the spirit of the classic games, so I really want the score to be formatted in this way. I see some solutions for this in JavaScript, but nothing in Swift.

like image 648
TheFutureOfWhat Avatar asked Dec 05 '25 02:12

TheFutureOfWhat


1 Answers

The literal 000000000 means the same thing as 0 to the compiler.

You can use stringWithFormat: to add leading zeros when converting to a string (assuming you have import Foundation):

String(format: "%09ld", score)
like image 172
jtbandes Avatar answered Dec 06 '25 17:12

jtbandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!