How to convert a numeric value into a percentage (

2019-02-09 07:31发布

问题:

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

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

The problem though is that the output becomes:

width: 35.13909224011713 '%';

How do I make it workable? ie.:

width: 35.13909224011713%;

回答1:

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().



回答2:

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.



回答3:

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.



标签: css less