How to convert a numeric value into a percentage (or) append percentage symbol to a number?

天大地大妈咪最大 提交于 2019-11-30 13:04:43
ldiqual

It is possible to use string interpolation:

@myvar: ((480/1366)*100);
width: ~"@{myvar}%";

That will output

width: 35.13909224011713%;

Additionally, if you want it to be rounded, you can use round().

Even though this question is quite old, I want to add a few more examples about adding. Less will set your units to whatever is being operated on.

10px + 20px

will output 30px

(20/200) * 100%

will output 10%

So with units you dont need to concatenate the unit measurement.

I have found that adding 0 helps when you dont know what the unit value might be.

.mixin(@x, @y){
    @result: (@x / @y) * 100;
}

.my_class {
    .mixin(20, 100);
    width: @result + 0%; // you can use any unit here
}

The above class will have a width of 20%. If we added with px, it would be 20px.

For some reason the least verbose and most obvious method is sort of missing here (it's in Richard Testani answer actually but there it's hindered with further code leading to a wrong direction). So... The answer to original:

width: ((480/1366)*100)+'%';

is as simple as:

width: (480/1366*100%);

Speaking of percentage:

it does the trick too but personally I'd never use it for its verbosity and non-readability. At quick scanning percentage(480/1366) reads just like peekabooze(480/1366) so you have to stop and stare at it to get a clue. Contrary the explicit appearance of % in 480/1366*100% (or 480 / 1366 * 100%) makes it more easily noticeable.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!