开发者

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

I'm trying to use LESS css to do the following:

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

The probl开发者_StackOverflow中文版em though is that the output becomes:

width: 35.13909224011713 '%';

How do I make it workable? ie.:

width: 35.13909224011713%;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜