解析英尺和英寸格式的字符串并转换为英寸作为浮点值

问题描述 投票:0回答:4

在我的数据库中,有一个名为

height
的字段,它是一个
varchar(9)
字段。最终用户从包含以下值的下拉列表中选择一个值:

5'0
5' 0 1/2
5'1
5' 1 1/2
5'2
5' 2 1/2
等等直到...
7' 4

我需要做的是将这个字符串转换为数字英寸,以便服务器端计算。这怎么办?

php math data-conversion text-parsing units-of-measurement
4个回答
1
投票

您想首先获得英尺、英寸和分数的单独变量

$toBeConverted = "5' 4 1/2";
list($feet,$inches,$frac) = explode(' ',$toBeConverted . ' ');

然后添加这些值

$total = ((str_replace("'",'',$feet) * 12) + $inches + ($frac == '1/2' ? (1/2) : 0));

0
投票
$inches=0;
$array=explode(" ",$string);//where $string is "5' 0 1/2" for example
if ($array[2]='1/2') $inches=(int)$array[0]*12+(int)$array[1]+0.5;
    else $inches=(int)$array[0]*12+(int)$array[1];

0
投票

如果你知道下拉的索引,第一个值为0,那么英寸数是

$inches = 60 + $pulldownIndex * 0.5;

因为您从

5'
(5 * 12 = 60) 开始,并以 0.5 英寸的增量上升。

或者,如果您想查看下拉列表中的字符串,我建议您查看 Felix 的答案 - 它非常紧凑且优雅。


0
投票

sscanf()
绝对是解析格式化字符串的最干净的工具。它比
preg_match()
更好,因为它不会创建不需要的全字符串匹配,并且可以将所有子字符串解析为整数。

sscanf()
的同一个家族中,
printf()
是一种理想的方式,可以将结果截断为指定的小数位数,并在浮点值旁边写入附加文本(例如
inches
)。

代码:(演示

$tests = [
    "5'",
    "5' 0",
    "5' 0 1/2",
    "5' 1",
    "5' 1 1/2",
    "5' 2",
    "5' 2 1/2",
    "7' 4",
];

foreach ($tests as $test) {
    sscanf($test, '%d\' %d %d/%d"', $feet, $inches, $numerator, $denominator);
    printf("%.1f\n", ($feet * 12) + $inches + ($denominator ? $numerator / $denominator : 0));
}

输出:

60.0
60.0
60.5
61.5
61.5
62.5
62.5
88.5
© www.soinside.com 2019 - 2024. All rights reserved.