php將字符串轉(zhuǎn)為小數(shù)的方法:1、使用number_format()函數(shù),語法“number_format($str,小數(shù)位數(shù)值)”;2、利用sprintf()函數(shù)格式化字符串,語法“sprintf("%.小數(shù)位數(shù)值f",$str)”。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
php將字符串轉(zhuǎn)為小數(shù)的方法
如果是一個(gè)包含小數(shù)的字符串,可以使用round()函數(shù)來將字符串轉(zhuǎn)為數(shù)值,并保留指定位數(shù)的小數(shù)。
但如果不包含小數(shù),怎么讓字符串轉(zhuǎn)化的數(shù)值有小數(shù)位呢?下面介紹兩種方法:
1、利用千位分組來格式化數(shù)字的函數(shù)number_format()
<?php $str = "12"; echo number_format($str, 2);; ?>
2、利用sprintf格式化字符串
<?php $str = "12"; echo sprintf("%.2f",$str); echo "<br>"; $str = "12.jg"; echo sprintf("%.2f",$str); ?>
推薦學(xué)習(xí):《PHP視頻教程》