简体   繁体   中英

convert digit into string in javascript

I have a number which represent time and I need to convert this number into string.

Like n = 800 , it represent time = 8:00

Currently I am doing this:

n = 800;
string time = '' +  n/100 + ' : ' + n % 100  ;

but time become 8 : 0 but I want to minutes in two digit format like 8 : 00 Anybody please help me there?

var n = 800;    
var hours = Math.floor(n/100);
var minutes = ('0' + (n%100)).slice(-2);
var time = hours + ':' + minutes;

Note the rounding on hours as well, otherwise you could end up with something like "8.56:56".

If all you are trying to do here is insert a colon before the last two digits you can just do a string replace:

var time = ("" + n).replace(/(\d\d)$/,":$1");

Or slice out the hours and minutes and concatenate with a colon:

var time = "" + n;
time = time.slice(0,-2) + ":" + time.slice(-2);

Just a shortcut solution :P

var a = 800;
var b = a.toString();
var first = b.replace(b.substring(b.length - 2),":"+b.substring(b.length - 2));

http://jsfiddle.net/6pfhyhhg/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM