2

I want to write a macro to set line height in fraction.

  font-size: 18px;
  line-height: 22px;

The problem is with expression register. I set 2 variables @f = font-size @h = line-height

And

=@h/@f - will be always integer. 

I know to get float, need one of arguments to be float, but the variables are integer.

Also prinf dont work

printf("%f", @h/@f) = will be integer(22/4) = 5, not 5.2

Thanks in advance

1
  • Did you found an answer to your question? Is one of the posted answer answering your question? If so I'll be glad if you could accept one of them. It allow the question to rest :-) Apr 3 at 14:43

3 Answers 3

2

The content of a register is either a string or a list. In this case, both @h and @f are strings so you leave the coercion to :h expr-/, which takes the shortest path possible because there is no indication that any of the operands should be considered as a float: coercion to numbers.

But you can coerce strings into floats with :help str2float(), so your expression should become:

=str2float(@h)/str2float(@f)
2

If instead of registers you used variables, you could make them floats directly:

:let h = 22.0
:let f = 4.0
…
=h/f

Or, you could "coerce" them:

:let h = 22
:let f = 4
…
=(h + 0.0)/f

With registers, you could "recall" one to coerce it, like

=<C-r>h.0/@f
1

I would use the str2float function.

printf("%f", str2float(@h)/str2float(@f))

Vim converts string into number when doing arithmetic but assuming strings are integers. If you want Vim to consider them as float you have to explicitly convert them into float using str2float.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.