I've got this question on my study guide: "Write an EBNF grammar description for Java float literals and one for Java double literals."

I've browsed the Oracle site and found the grammar for java float literals, but I'm not entirely sure how to convert that to EBNF grammar. I understand EBNF notation but for some reason I'm stuck on this.

I was hoping/wondering someone would be able to get me started? It would be highly appreciated.


You could try answer the question "How do I define double and float literals?"

doubles are usually defined as:

double a = 12d;
double b = 12.1;
double c = 12.1d;
double d = 12;

while floats could be defined as:

float m = 10;
float n = 10.4f;
//but this is invalid:
float p = 10.4;

Note that by default a literal like 10.123 is considered to be double, so if you really want to assign it to a float variable, you need to append a f character in the end. However, f is optional when the literal is 10.

Let's also list the properties of both types:

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (up to 9 decimal digits). 8 bits are used for the exponent, so a float can move the decimal point to the right or to the left using those 8 bits. There is 1 bit used as the sign bit. The max long value that double can hold is $10_18$

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (up to 19 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

So, double and float could be defined like:

digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";

double = 19 * digit, [ [, | .]  18 * digit]["d" | "D"];
float = 19 * digit, [ [, | .]  18 * digit, "f" | "F"];
  • 4
    $\begingroup$ "...19 * digit..." - I'm not sure I understand this part. If you mean "up to 19 decimal digits", then usually grammars are not so precise, they describe overall structure, but not precise limits. You might want to take a look at the actual grammar for Java floating-point literals. It is actually trivial to translate their notation into EBNF. $\endgroup$ Feb 18 '16 at 15:54
  • $\begingroup$ That helped. But where could I find the grammar for doubles? I didn't seem to see it on that page. $\endgroup$
    – Mkey
    Feb 18 '16 at 18:11
  • $\begingroup$ @AntonTrunov, yes, it's up to 19. $\endgroup$ Feb 18 '16 at 20:08
  • 1
    $\begingroup$ @Mkey That grammar covers both floats and doubles; it doesn't distinguish between the two. Note that FloatTypeSuffix can produce f, F, d, or D. $\endgroup$
    – DylanSp
    Feb 18 '16 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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