Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

floating point - PHP division adds a comma

I'm trying to convert cents to dollars (I don't need dollar sign, just value) but when I divide a number smaller than 100 by 100 I get a strange result.

Eg.: 1/100 give me 0,01.0

I don't need that comma, I need 0.01 as it should be.

I also tried number_format but it returns a string and when I cast the result to float I get the same strange value.

How can I fix it?

Thanks in advance for your help

This is the function I'm using:

public static function convertFromCents($value) {
    if(is_numeric($value)) {
        $value = $value/100;
    } else {
        $value = 0;
    }

    return $value;
}

This are the proof of what I'm saying: enter image description here

enter image description here

question from:https://stackoverflow.com/questions/65888950/php-division-adds-a-comma

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

1 Reply

0 votes
by (71.8m points)

It looks like what you see are messages of your IDE, not the real value of your variable.

In order to achieve what you want, you can simply use round function.
The second parameter is precision, which determines how many digits will appear after the point:

// return 0.33333333333333
echo 1/3;

// return 0.33
echo round(1/3, 2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...