PHP - 强制整数转换为带有三位小数的浮点数

PHP - Force integer conversion to float with three decimals(PHP - 强制整数转换为带有三位小数的浮点数)
本文介绍了PHP - 强制整数转换为带有三位小数的浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将大量数字转换为特定格式,即 +/-NNN.NNN.所以,如果我有这些数字:

I am trying to convert a big array of numbers to a specific format which is +/-NNN.NNN. So, if I have these numbers:

$numbers1 = array(-1.23, 0.3222, 10, 5.54);

我希望他们的最终格式是

I want their final format to be

$numbers2 = array(-001.023, +000.322, +010.000, +005.054);

我正在尝试这样做:

foreach ($numbers1 as $n) {
 $fnum = abs(number_format((float)$n, 3, '.', ''));
 if ($fnum>0 && $fnum<10) { 
     $fnum = '00'.$fnum;
 } else if ($fnum >= 10 && $fnum<100) {
     $fnum = '0'.$fnum;
 }
 if ($n>0) $fnum = '+'.$fnum;
 if ($n<0) $fnum = '-'.$fnum;
 if ($n == 0) $fnum = '+000.000';
 $numbers2[] = $fnum;

}

这是错误的,我只是不知道要使用什么来实现它.

This is wrong and I just don't know what to use in order to achieve it.

推荐答案

尝试使用 sprintf()

$numbers2[] = sprintf("%+07.3f", $fnum);

这篇关于PHP - 强制整数转换为带有三位小数的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)