简体   繁体   English

在jQuery中格式化数字

[英]Formatting Number in jQuery

I am creating an app with Phonegap and JQuery Mobile and have a particular scenario where I need to format a particular counter. 我正在使用Phonegap和JQuery Mobile创建一个应用程序,并且我需要格式化特定计数器。

Basically the counter starts from 1 and keeps increasing showing the distance travelled. 基本上计数器从1开始并且持续增加显示行进的距离。 However, in order to display it I need to display them as 0001 then once an event is triggered it goes to 0002 .... 0099... 0999... 9999 (max). 但是,为了显示它我需要将它们显示为0001然后一旦触发事件它就会转到0002 .... 0099 ... 0999 ... 9999(最大)。

The issue is that when the distance travelled is less than 1KM, I need to show the decimal point. 问题是当行进的距离小于1KM时,我需要显示小数点。 Therefore since I am limited to show the 4 digits, I need to show the distance as: 0.250KM (which would be equivalent to 250m). 因此,由于我仅限于显示4位数字,我需要将距离显示为:0.250KM(相当于250米)。

Can anyone tell me how I can achieve this so that once the number is less than 1, it shows up as for example 0.005 then 0.025, then 0.250, until it hits 0.999 which then it would round to 0001. 任何人都可以告诉我如何实现这一点,以便一旦数字小于1,它会显示为例如0.005然后是0.025,然后是0.250,直到它达到0.999然后它将会转到0001。

At the moment I had this setup: 目前我有这个设置:

var newDist = Math.round((geoLocationHandler.distance/1000)); // shows distance in KM
var distance = parseInt($('.distanceTravelled').text(), 10);
$('.distanceTravelled').text(("000"+ (distance+newDist)).slice(-4)); 

And HTML 和HTML

<span class="distanceTravelled">0000</span>km

Try this: 尝试这个:

function padNumber(number, padding, length) {
    var string = (Math.round( number * 1000 ) / 1000)+ '';
    if(number < 1 && number != 0){
        while (string.length <= length){
            string += padding;
        }
    } else {
        while (string.length < length){
            string = padding + string;
        }
    }
    return string;
}

padNumber(0.23, 0, 4);
//"0.230";
padNumber(23, 0, 4);
//"0023";
padNumber(23.5, 0, 4)
//"0024"
padNumber(0.95512154, 0, 4)
//"0.950"

Keep in mind that this doesn't add the 'KM' suffix, yet. 请记住,这还没有添加'KM'后缀。 You could do that with: 你可以这样做:

return string + 'KM';

It's crazy but works: 这很疯狂但有效:

var a = .999;

function padder(a) {
    var hasDecimal = $.inArray('.', a.toString().split('')) !== -1,
        b = (hasDecimal ? a.toFixed(3): a.toString()).split(''),
        zeros = hasDecimal ? '00000' : '0000';

    return $.map(zeros.split(''), function (i) {
       return b.pop() || i;
    }).reverse().join('');
}

the reverse() is used to fix the pop() action. reverse()用于修复pop()动作。 I use pop to guarantee I'm the rightmost digits at the beginning of the array. 我使用pop来保证我是数组开头的最右边数字。 So, ".250" would go -> 0, 5, 2, ., 0 . 所以,“。250”将会-> 0, 5, 2, ., 0 0,5,2 -> 0, 5, 2, ., 0 I need to reverse that and join the array back into a string. 我需要反转它并将数组连接回一个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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