[英]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 像n = 800,它代表时间= 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? 但是
time
变成了8 : 0
但是我想用两位数字格式分钟,比如8 : 00
任何人请帮助我吗?
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". 注意小时数的四舍五入,否则你最终会得到像“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 只是一个捷径解决方案:P
var a = 800;
var b = a.toString();
var first = b.replace(b.substring(b.length - 2),":"+b.substring(b.length - 2));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.