IBRA
IBRA

Reputation: 143

how can i add "point" before the last two numbers

How can I add a point before the last two numbers?

Lets say numbers is

299 , 250 , 400 , 4500 , 20099

I want to get last two digit and add point befor it

i.e

2.99 , 2.50 , 45.00 , 200.99

using php

Upvotes: 0

Views: 1025

Answers (4)

Steve
Steve

Reputation: 818

Have I missed something or wouldn't this do it - from php.net - the manual.

 $number = 1234.5678;

 // english notation without thousands separator
 $english_format_number = number_format($number, 2, '.', '');
 // 1234.57

http://php.net/manual/en/function.number-format.php

Substring_replace is the simpler option as per version by @Roadirsh, which would do what is really asked for. Sean's version will also work as per comment by @sean number_format($number/100, 2, '.', ''); (included here in case comments get deleted). My version will only handle numbers with existing decimal points or add .00

Although expected behaviour was that numbers would be rounded, further testing shows that they are not rounded if they are already only two places of decimals as in the /100 part. They are rounded if more decimal places are present.

I would have deleted my version but it might be of use to have here.

Upvotes: 1

userlond
userlond

Reputation: 3828

How about using number_format and array_map?

<?php
$numbers = explode(' , ', '299 , 250 , 400 , 4500 , 20099');
$numbersHandled = array_map(function($e) {
    return number_format($e/100, 2, '.', '');
}, $numbers);

print_r($numbersHandled);

Check runnable.

Upvotes: 1

Roadirsh
Roadirsh

Reputation: 572

You could use the function substr-replace

substr_replace('299','.',-2,0);

Upvotes: 5

chris85
chris85

Reputation: 23892

You could use a regex.

echo preg_replace('/(\d+)(\d{2})/', '$1.$2', '299 , 250 , 400 , 4500 , 20099');

Output:

2.99 , 2.50 , 4.00 , 45.00 , 200.99

Demo: https://regex101.com/r/hY1zM6/1

Upvotes: 0

Related Questions