Alex
Alex

Reputation: 21

M4 eval precision

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!

Upvotes: 2

Views: 623

Answers (2)

abernier
abernier

Reputation: 28238

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

Upvotes: 0

Giuseppe Guerrini
Giuseppe Guerrini

Reputation: 4438

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.

Upvotes: 1

Related Questions