Nikola Nastevski
Nikola Nastevski

Reputation: 927

How to make the decimals superscript, or subscript, in PHP?

I have this code:

<?php echo $price; ?>

which gives me this result:

1,500.99

Is there any way I can make the decimals superscript or subscript?

Thanks.

EDIT: This code works like a charm (thanks to David Thomas):

$parts = explode('.', $price); 
echo "$parts[0].<sup>$parts[1]</sup>";

but if I have a price like this: 1,500.99€ it superscripts the € sign as well. Can this be stoped? To not superscript it if it's not a number, or to superscript only 2 characters after the dot?

Upvotes: 1

Views: 12650

Answers (4)

Vipin Jain
Vipin Jain

Reputation: 1402

check this code:

<?php
$val = 10009.99;
echo set_sub_dec($val);

function set_sub_dec($val,$type="sub",$attrib=""){//use "sub" or "sup" or any other HTML tag with attributes
    if(!is_string($val)){
        $val = strval($val);
    }

    $val = split("\.",$val);

    return $val[0].".<$type $attrib>".$val[1]."</$type>";
}

?>

Upvotes: 0

David Thomas
David Thomas

Reputation: 253396

This is currently untested, but I think that's as simple as:

$parts = explode('.', $price);
echo "$parts[0].<sup>$parts[1]</sup>";

References:

Upvotes: 8

Ozzy
Ozzy

Reputation: 8312

With HTML and CSS, here is an example:

<style type="text/css">
.superscript {
    font-size: xx-small;
    vertical-align: top;
}
.subscript {
    font-size: xx-small;
    vertical-align: bottom;
}
</style>

<body>

<table>
<td class="superscript"><?php echo $price ?></td>
<td class="subscript"><?php echo $price ?></td>
</table>

Upvotes: 0

Lorenzo Marcon
Lorenzo Marcon

Reputation: 8169

You can use html sub and sup tags: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_sup

An example code could be:

echo preg_replace('/\.([0-9]*)/', '<sup>.$1</sup>', $price);

Upvotes: 3

Related Questions