I want to convert numbers like below in php
EX1: 0.00004123456 => 0.00004
EX2: 0.000000004123456 => 0.000000004
EX3: 2.04123456 => 2.04
EX4: 2.44123456 => 2.4
I did not get results from the round()
and more solutions
I want to convert numbers like below in php
EX1: 0.00004123456 => 0.00004
EX2: 0.000000004123456 => 0.000000004
EX3: 2.04123456 => 2.04
EX4: 2.44123456 => 2.4
I did not get results from the round()
and more solutions
2
Answers
Let’s do it as we would manually. Convert to string. Find a
.
and then the first non0
char.substr
then turn to number back.Output:
You can do it with a regex.
Which outputs:
Test it here.
Explanation
The regular expression which was used functions like this (as explained in this regex101.com snippet ):
^
asserts position at start of a line-
matches the dash character?
matches the previous dash between zero and one times. This is done to handle cases when there are both positive and negative integersd
matches a digit (equivalent to [0-9])+
matches the previous token between one and unlimited times, as many times as possible,.
matches the decimal point?
matches the previous decimal point between zero and one times. This is used to handle cases when there are integers and decimal numbersd
as before, this matches a digit(
and)
are used to denote our capturing group and all the possible alternatives[1-9].*?
– this is the first alternative. We’re matching all the digits that can come after a decimal point, which are not zero0$
– this is the second alternative. It’s for handling cases when a number is a zero only number