Formatting a number as currency using CSS

前端 未结 4 956
北海茫月
北海茫月 2020-12-15 15:32

Just wondering if anyone knows whether it is possible to format the content of an element as currency using only CSS. It would be nice to have how the value is presented in

4条回答
  •  醉酒成梦
    2020-12-15 15:51

    Well, this doesn't fit your own use case unfortunately, and it's fairly obvious, but you could do this for integer numbers from -999 to 999.

    .currency:before{ content:'$'; }
    .currency:after{ content: '.00'; }
    789

    Then, a possible, annoying, solution if you're working server side, is to convert your number to a reversed string and loop over each character. If you really wanted you could place the characters into li's and css could then do the formatting you wanted as follows. However this is incredibly pointless as you may as well simply author the string at that point.

    .currency li:before{ content: ' ,';}
    .currency li:first-child:before{ content:'$' !important; }
    .currency *{ display: inline-block; }
    .currency, .currency > *{ display: inline-block; }
    .currency:after{ content: '.00'; }
    • 123
    • 456
    • 789
    • 456
    • 789
    • 789

    For an even deeper dive into pointless effort, you could prepend a

    
    

    above the

      , allowing your script to change the decimal value in CSS, lol

      Still, if you were to cave and use JavaScript, then the CSS may actually be somewhat useful. You can output a plain int or double (any precision) and just have JS break it into

    • s.

提交回复
热议问题