Home  >  Q&A  >  body text

javascript - How to make a string automatically add 0 in front of a single digit and only retain two digits of a three-digit number

Get data from the background. If the data is "4", the front desk will display "04". If the background is "04", the front desk will display "04"

My code:
$(".ball_1").html(data.ball_1>=10||data.ball_1.length=3data.ball_1:'0' data.bal_1||data.ball_1.substring (1));
Report an error directly

$(".ball_1").html(data.ball_1>=10?data.ball_1:'0' data.ball_1&&data.ball_1.length>=3?data.ball_1.substring(1)?data.ball_1 );

If the data is "4", it will display 4. How should this function be implemented?

巴扎黑巴扎黑2663 days ago973

reply all(4)I'll reply

  • 某草草

    某草草2017-07-05 10:55:42

    If the data is "4", the front desk will display "04". If the background is "04", the front desk will display "04"

    For example
    "1" => "01"
    "4" => "04"
    "99" => "99"


    Use slices

    var addPrefix = str => ('00' + str).slice(-2); 

    This can do what you need: pad zeros for one digit and retain only two digits for three digits


    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:55:42

    var num = '1';

    num = Number(num);

    num = num<10? '0'+num : num;

    //What does it mean to keep two digits in a three-digit number? ? ? ?
    //num = (num==100 || num>100)? ... : ...

    reply
    0
  • ringa_lee

    ringa_lee2017-07-05 10:55:42

    function x(d){
        D=d<10?`0${d}`:`${d}`.match(/^\d{2}/)[0];return D
    }

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-07-05 10:55:42

    parseInt('04')<10?'0'+parseInt('04'):'04'

    reply
    0
  • Cancelreply