M4 eval precision

核能气质少年 提交于 2019-12-22 11:33:46

问题


I'm trying to use M4 macros to generate css files. I'm willing to enter my values in px and do simple math using eval() to get results in em. Unfortunatly I didn't find how to get floats.

define(`FONTSIZE', `13')dnl
define(`LINEHEIGHT', `17')dnl
.content {padding : eval(LINEHEIGHT / FONTSIZE)em}
>>> m4 style.css.m4
>>> .content {padding : 1em}

Any ideas?

Thanks!


回答1:


For your particular purpose the expression may become something like

eval(LINEHEIGHT/FONTSIZE).substr(eval(((LINEHEIGHT%FONTSIZE)*1000)/FONTSIZE + 1000),1)

(of course, use the power of 10 that meets your precision requirements) This is a common trick to obtain a floating point-like result from a division. Other operators are more complicated, not to say the functions like sin, cos, ln...

In general it would be possible in principle to write some floating point manipulation macros implemented with string manipulations and integer operators, but I think it's more pratical to use an external program (bc, gawk...) invoked by "syscmd()" when the operations are not as simple as a division.




回答2:


Inspired from previous answer:

define(`FONTSIZE', `13')dnl
define(`LINEHEIGHT', `17')dnl

.content {padding:syscmd(bc <<< "scale=6; print LINEHEIGHT/FONTSIZE")em;}

NB: scale=6; is for floating precision

NB: I've written a little macro for this, you can find it here: m4 preprocessor BC macro



来源:https://stackoverflow.com/questions/5442861/m4-eval-precision

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