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

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

php - Convert .5 into 1/2

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

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

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...