Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to convert any number which ends in .5 so that it displays as the number followed by ½, but I don't want 0.5 to display as 0½ so I did it like this:

$used = str_replace("0.5", "½", $used);
$used = str_replace(".5", "½", $used);

However I've now realised that this also converts 20.5 into 2½ instead of 20½.

I'm sure there's a better way of doing it but I don't know how.

Examples:

5 returns "5"
5.5 returns "5½"
0.5 returns "½"
10.5 returns "10½"

I don't believe this is a duplicate of an existing question because that code is to replace or return "1/2" rather than "½"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
356 views
Welcome To Ask or Share your Answers For Others

1 Answer

Based on the examples above and lacking any further requirements, you could write:

<?php

  $n = "13.5";
  /* ... */
  $r = $n;
  $r = preg_replace ('/^0.5$/', '&frac12;', $r);
  $r = preg_replace ('/.5$/', '&frac12;', $r);

  echo "$r
";

You can combine the above into a single replacement:

  $r = preg_replace ('/(^0|).5$/', '&frac12;', $n);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...